首頁 >後端開發 >php教程 >使用php的swoole框架,實現高效能長連接websocket

使用php的swoole框架,實現高效能長連接websocket

WBOY
WBOY原創
2016-07-29 09:14:391913瀏覽

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></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教程有興趣的朋友有所幫助。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn