如果想對(duì)一個(gè)列表做實(shí)時(shí)的更新,傳統(tǒng)的做法是采用輪詢的方式。以web為例,通過(guò)Ajax定時(shí)請(qǐng)求服務(wù)端然后獲取數(shù)據(jù)顯示在頁(yè)面。這種方式實(shí)現(xiàn)簡(jiǎn)單,缺點(diǎn)就是浪費(fèi)資源。
HTTP1.1新增加了對(duì)websocket的支持,這樣就可以將被動(dòng)展示轉(zhuǎn)變?yōu)橹鲃?dòng)通知。也就是通過(guò)websocket與服務(wù)端保持持久鏈接,一旦數(shù)據(jù)發(fā)生變化,由server通知client數(shù)據(jù)有更新,然后再進(jìn)行刷新等操作。這樣就省去了很多不必要的被動(dòng)請(qǐng)求,節(jié)省了服務(wù)器資源。
要實(shí)現(xiàn)一個(gè)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連接已打開(kāi)" ); }; ws.onmessage = function (e){ console.log( "message:" + e.data); }; ws.onclose = function (){ console.log( "socket連接已斷開(kāi)" ); }; ws.onerror = function (e){ console.log( "ERROR:" + e.data); }; //離開(kāi)頁(yè)面時(shí)關(guān)閉連接 $(window).bind( 'beforeunload' , function (){ ws.close(); } ); } |
這樣就實(shí)現(xiàn)了一個(gè)client,不過(guò)事情還遠(yuǎn)沒(méi)有結(jié)束。上面的代碼只是簡(jiǎn)單的進(jìn)行了連接,對(duì)話,關(guān)閉等基本動(dòng)作。如果想和服務(wù)端進(jìn)行通訊,必須要有更具體的方案。比如收到message時(shí)判斷類型進(jìn)行進(jìn)一步操作。
服務(wù)端:此處采用Swoole進(jìn)行php服務(wù)端的websocket開(kāi)發(fā),使用swoole進(jìn)行php的websocket開(kāi)發(fā)非常簡(jiǎn)單,而且它還支持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是一個(gè)php的擴(kuò)展,安裝方式可以參考這里:php安裝swoole擴(kuò)展的方法
本文先寫(xiě)到這里,下一篇會(huì)寫(xiě)一些更具體的操作,感興趣的朋友請(qǐng)繼續(xù)關(guān)注本站。謝謝!