如果想對一個列表做實時的更新,傳統的做法是采用輪詢的方式。以web為例,通過Ajax定時請求服務端然后獲取數據顯示在頁面。這種方式實現簡單,缺點就是浪費資源。
HTTP1.1新增加了對websocket的支持,這樣就可以將被動展示轉變為主動通知。也就是通過websocket與服務端保持持久鏈接,一旦數據發生變化,由server通知client數據有更新,然后再進行刷新等操作。這樣就省去了很多不必要的被動請求,節省了服務器資源。
要實現一個webscoket的程序,首先需要使用支持html5的瀏覽器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
if (ws === null){ var wsServer = 'ws://' + location.hostname + ':8888' ; ws = new WebSocket(wsServer); ws.onopen = function (){ console.log( "socket連接已打開" ); }; ws.onmessage = function (e){ console.log( "message:" + e.data); }; ws.onclose = function (){ console.log( "socket連接已斷開" ); }; ws.onerror = function (e){ console.log( "ERROR:" + e.data); }; //離開頁面時關閉連接 $(window).bind( 'beforeunload' , function (){ ws.close(); } ); } |
這樣就實現了一個client,不過事情還遠沒有結束。上面的代碼只是簡單的進行了連接,對話,關閉等基本動作。如果想和服務端進行通訊,必須要有更具體的方案。比如收到message時判斷類型進行進一步操作。
服務端:此處采用Swoole進行php服務端的websocket開發,使用swoole進行php的websocket開發非常簡單,而且它還支持httpserver的支持。
1
2
3
4
5
6
7
8
9
10
11
12
|
$server = new swoole_websocket_server( "0.0.0.0" , 8888); $server ->on( 'open' , function (swoole_websocket_server $server , $request ) { echo "server: handshake success with fd{$request->fd}\n" ; }); $server ->on( 'message' , function (swoole_websocket_server $server , $frame ) { echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n" ; $server ->push( $frame ->fd, "this is server" ); }); $server ->on( 'close' , function ( $ser , $fd ) { echo "client {$fd} closed\n" ; }); $server ->start(); |
swoole是一個php的擴展,安裝方式可以參考這里:php安裝swoole擴展的方法
本文先寫到這里,下一篇會寫一些更具體的操作,感興趣的朋友請繼續關注本站。謝謝!