基于 TCP 简单聊天室代码
<?php
// 存放用户数量以及状态
//创建Server对象,监听 127.0.0.1:9501 端口
$server = new Swoole\Server('0.0.0.0', 9502);
//监听连接进入事件
$server->on('Connect', function ($server, $fd) {
echo "Client: 用户{$fd}进入房间.\n";
});
//监听数据接收事件
$server->on('Receive', function ($server, $fd, $reactor_id, $data) {
// 用户发送格式 fd:xxxx
$data_arr = explode(':',$data);
// 发送用户的房间号
$send_fd = $data_arr[0];
// 发送的内容
$msg = $data_arr[1];
// 检测用户是否下线 $server->exist($send_fd)
if($server->exist($send_fd)){
// 发送
$server->send($send_fd, "用户{$fd}: {$msg}\n");
}else{
// 发送
$server->send($fd, "用户{$send_fd}下线或不存在\n");
}
if(trim($msg) == "close"){
$server->close($fd , true);
echo "{$fd}:close";
}
});
//监听连接关闭事件
$server->on('Close', function ($server, $fd) {
echo "Client: 用户{$fd}退出房间.\n";
});
//启动服务器
$server->start();
运行代码:
当用户1 发信息给用户2时:
用户2收到用户1的信息:
退出聊天室:
上面就时一个简单的聊天功能, 在代码里面,监听 数据接受事件 ,把 发送的数据进行拆分,可实现想要的功能 如 server_chat.php 文件中: