本文共 3404 字,大约阅读时间需要 11 分钟。
最近自学了swoole,想做点东西试试看,刚好看到可以简单做个聊天室,于是自己研究研究搞了一个。
websocket是不同于http的另外一种网络通信协议,能够进行双向通信,基于此,可开发出各种实时通信产品,我简单做了个聊天室demo,顺便分享一下。
这里我简单把websocket服务器分配的fd(文件描述,可以理解为用户id)在文本(user.txt),然后进行遍历群发送消息,不啰嗦,核心代码如下:
websocket.php
server = new swoole_websocket_server("0.0.0.0", 9502); //监听WebSocket连接打开事件 $this->server->on('open', function (swoole_websocket_server $server, $request) { echo "server: handshake success with fd{$request->fd}\n"; $array = []; if (file_exists($this->userFile)) { $array = array_filter(explode(',', file_get_contents($this->userFile))); } array_push($array, $request->fd); file_put_contents($this->userFile, join(',', $array), LOCK_EX); }); //监听WebSocket消息事件 $this->server->on('message', function (swoole_websocket_server $server, $frame) { echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n"; //获取聊天用户数组 $array = explode(',', file_get_contents($this->userFile)); foreach ($array as $key => $val) { $array[$key] = intval($val); } //组装消息数据 $msg = json_encode([ 'fd' => $frame->fd,//客户id 'msg' => $frame->data,//发送数据 'total_num' => count($array)//聊天总人数 ], JSON_UNESCAPED_UNICODE); //发送消息 foreach ($array as $fdId) { $server->push($fdId, $msg); } }); //监听WebSocket连接关闭事件 $this->server->on('close', function ($server, $fd) { //获取聊天用户数组 $array = explode(',', file_get_contents($this->userFile)); foreach ($array as $key => $val) { $array[$key] = intval($val); } ///组装消息数据 $msg = json_encode( [ 'fd' => $fd, 'msg' => '离开聊天室!', 'total_num' => count($array) - 1 ], JSON_UNESCAPED_UNICODE); //发送消息 foreach ($array as $key => $fdId) { if ($fdId == $fd) { unset($array[$key]); } else { $server->push($fdId, $msg); } } //更新聊天用户数组 file_put_contents($this->userFile, join(',', $array), LOCK_EX); echo "client {$fd} closed\n"; }); //监听Http请求事件 $this->server->on('request', function ($request, $response) { // 接收http请求从get获取message参数的值,给用户推送 // $this->server->connections 遍历所有websocket连接用户的fd,给所有用户推送 foreach ($this->server->connections as $fd) { $this->server->push($fd, $request->get['message']); } }); $this->server->start(); }}new Websocket();
安装完php 和swoole扩展之后,直接执行:
php websocket.php
并可以观察下输出,看看websocket服务器是否正常。
效果如下:
1代码中不要用,exit()/die(),socket会报 ERROR zm_deactivate_swoole (ERROR 9003): worker process is terminated by exit()/die(),因为子进程没有处理就退出了,主进程又会重新拉起。这样就造成死循环了。2.进程隔离也是很多新手经常遇到的问题。修改了全局变量的值,为什么不生效,原因就是全局变量在不同的进程,内存空间是隔离的,所以无效。3.因为我的代码都是在虚拟机上跑,想让其他PC访问,需要做NAT端口映射。其中,192.168.1.119是我本地ip,192.168.33.10是我虚拟机的ip,socket服务是在虚拟机的9520端口跑的,最后前端代码的socket端口也相应改下就可以了。
前后端代码在我的git有,有兴趣的同学自行下载~
git地址:
欢迎star!参考:
NAT端口映射:swoole手册:转载于:https://blog.51cto.com/onebig/2058144