//创建Server对象,监听 127.0.0.1:9501 端口
$server = new Swoole\WebSocket\Server("0.0.0.0", 9501);
//监听连接进入事件
$server->on('open', function (Swoole\WebSocket\Server $server,Swoole\Http\Request $request) {
echo "Client: Connect.\n";
});
//监听数据接收事件
$server->on('message', function (Swoole\WebSocket\Server $server,swoole_websocket_frame $frame) {
session_start();
$data=json_decode($frame->data);
if($data->type==1){
$_SESSION[$data->user]=$frame->fd;
}else{
$fd=$_SESSION[$data->user];
$server->push($fd, $data->msg);
}
});
//监听连接关闭事件
$server->on('close', function ($ser, $fd) {
echo "Client {$fd} Closed\n";
});
//启动服务器
$server->start();
|