用swoole扩展编写WebSocket聊天室

来源:互联网 发布:淘宝封号能自动解封吗 编辑:程序博客网 时间:2024/05/24 02:16

最近正在接触swoole扩展 先写个简单的swoole聊天室demo吧

<!DOCTYPE html><html><head>  <title>swoole chatroom</title>  <meta charset="UTF-8">  <script type="text/javascript">   var exampleSocket = new WebSocket("ws://0.0.0.0:9501");   exampleSocket.onopen = function (event) {    exampleSocket.send("连接!");    };   exampleSocket.onmessage = function (event) {    var chat_room = document.querySelector("#chatroom");    var data = event.data;    var chat_list = document.createElement("li");    var chat_content = document.createTextNode(data);    chat_list.appendChild(chat_content);    chat_room.appendChild(chat_list);      }  </script></head><body> <input type="text" id="content"> <button onclick="exampleSocket.send( document.getElementById('content').value )">发送</button> <div id="chatroom">  <ul id="chatlist">  </ul> </div></body></html>

用的是连接方式是WebSocket

使用将onopen绑定到WebSocket事件原因是因为建立WebSocket的方式是异步的,所以要在其成功建立对象时确定连接是否成功

onmessage是接受消息时触发的方法

<?php$server = new swoole_websocket_server("0.0.0.0", 9501);$max = 0;$server->on('open', function (swoole_websocket_server $server, $req) {    //每一次客户端连接 最大连接数将增加    global $max;    $max++;});$server->on('message', function (swoole_websocket_server $server, $frame) {    $fd   = $frame->fd;    $data = $frame->data;    $message = "连接号{$fd}:内容:{$data}";    global $max;    //向所有人广播    for ($i = 1; $i <= $max; $i++) {        echo PHP_EOL . time('Y-m-d h:m:s') . ': ' . $fd . " : " . $data;        $server->push($i, $message);    }});$server->on('close', function (swoole_websocket_server $server, $fd) {    //关闭连接 连接减少    global $max;    $max--;    echo "client {$fd} closed\n";});$server->start();

服务端的原理:

全局变量$max存储连接数,每当发生一个WebSocket连接时,$max加一

取得连接后,用push向所有连接进行广播

关闭连接时,连接数减少

然而这仍然存在一些问题 比如当浏览器刷新的时候 没有close掉旧的连接 而是又创建了一个新的连接

这些在该demo里都没有得到处理

2 0