1.放行防火墙及宝塔安全端口号


2.配置解析过的域名

3.讲文件配置到根目录下

4.创建websocket.php文件,访问聊天页面web.html
websocket.php
<?php
//创建WebSocket Server对象,监听0.0.0.0:9502端口
$ws = new Swoole\WebSocket\Server('0.0.0.0', 9502);
//监听WebSocket连接打开事件
$ws->on('Open', function ($ws, $request) {
//进行数据组装
$arr=[
'type'=>'open',
//唯一标识
'fd'=>$request->fd
];
//将组装好的数据编码,推给客户端
$ws->push($request->fd, json_encode($arr));
});
//监听WebSocket消息事件
$ws->on('Message', function ($ws, $frame) {
//这里的echo就是在终端上显示的那些服务端给客户端的消息
echo "Message: {$frame->data}\n";
//解码
$arr=json_decode($frame->data,true);
//判断
switch ($arr['type']) {
//登录
case 'login':
$res=[
'type'=>'login',
'fd'=>$frame->fd,
'content'=>'欢迎'.$arr['nickname'].'进入聊天室'
];
foreach ($ws->connections as $fd){
$ws->push($fd,json_encode($res));
}
break;
//聊天
case 'chat':
$res=[

最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



