Maison > Article > développement back-end > 使用php的swoole框架,实现高性能长连接websocket
swoole的官网请见:http://www.swoole.com/
swoole-git:https://github.com/swoole/swoole-src
一.服务器端:
1. 编辑server.php文件内容如下:
<code><span><span><?php </span><span>$reqs</span>=<span>array</span>(); <span>//保持客户端的长连接在这个数组里</span><span>$serv</span> = <span>new</span> swoole_websocket_server(<span>"192.168.2.115"</span>, <span>9502</span>); <span>//如下可以设置多端口监听</span><span>//$server = new swoole_websocket_server("0.0.0.0", 9501, SWOOLE_BASE);</span><span>//$server->addlistener('0.0.0.0', 9502, SWOOLE_SOCK_UDP);</span><span>//$server->set(['worker_num' => 4]);</span><span>$serv</span>->on(<span>'Open'</span>, <span><span>function</span><span>(<span>$server</span>, <span>$req</span>)</span> {</span><span>global</span><span>$reqs</span>; <span>$reqs</span>[]=<span>$req</span>->fd; <span>echo</span><span>"connection open: "</span>.<span>$req</span>->fd.<span>"\n"</span>; var_dump(count(<span>$reqs</span>));<span>//输出长连接数</span> }); <span>$serv</span>->on(<span>'Message'</span>, <span><span>function</span><span>(<span>$server</span>, <span>$frame</span>)</span> {</span><span>global</span><span>$reqs</span>; <span>echo</span><span>"message: "</span>.<span>$frame</span>->data.<span>"\n"</span>; <span>foreach</span>(<span>$reqs</span><span>as</span><span>$fd</span>){ <span>$server</span>->push(<span>$fd</span>, <span>$frame</span>->data); } }); <span>$serv</span>->on(<span>'Close'</span>, <span><span>function</span><span>(<span>$server</span>, <span>$fd</span>)</span> {</span><span>echo</span><span>"connection close: "</span>.<span>$fd</span>.<span>"\n"</span>; }); <span>$serv</span>->start();</span></span></code>
2. 启动上面实现的websocket服务代码
<code>[songaimin<span>@localhost</span><span>Tests</span>]<span>$/</span>usr/bin/php server.php</code>
客户端-同事打开两个浏览器模拟多client:
3. 在浏览器console里运行:
<code>ws = <span>new</span> WebSocket(wsl);<span>//新建立一个连接</span><span>//如下指定事件处理 </span> ws.onopen = <span><span>function</span><span>()</span>{</span>ws.send(<span>'Test!'</span>); }; ws.onmessage = <span><span>function</span><span>(evt)</span>{</span>console.log(evt.data);<span>/*ws.close();*/</span>}; ws.onclose = <span><span>function</span><span>(evt)</span>{</span>console.log(<span>'WebSocketClosed!'</span>);}; ws.onerror = <span><span>function</span><span>(evt)</span>{</span>console.log(<span>'WebSocketError!'</span>);}; </code>
4. 在任意浏览器console里手动执行:
<code>ws.send<span>(888</span>); <span>//看每个浏览器的内容console输出应该是一样的就实验在成功了</span> ws.<span>close</span>();<span>//关闭连接</span></code>
相关推荐文章:
swoole实现的实时聊天室 http://segmentfault.com/a/1190000003057118
以上就介绍了使用php的swoole框架,实现高性能长连接websocket,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。