程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> 使用php+swoole對client數據實時更新(一),swooleclient

使用php+swoole對client數據實時更新(一),swooleclient

編輯:關於PHP編程

使用php+swoole對client數據實時更新(一),swooleclient


如果想對一個列表做實時的更新,傳統的做法是采用輪詢的方式。以web為例,通過Ajax定時請求服務端然後獲取數據顯示在頁面。這種方式實現簡單,缺點就是浪費資源。

HTTP1.1新增加了對websocket的支持,這樣就可以將被動展示轉變為主動通知。也就是通過websocket與服務端保持持久鏈接,一旦數據發生變化,由server通知client數據有更新,然後再進行刷新等操作。這樣就省去了很多不必要的被動請求,節省了服務器資源。

要實現一個webscoket的程序,首先需要使用支持html5的浏覽器

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的支持。

$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擴展的方法

本文先寫到這裡,下一篇會寫一些更具體的操作,感興趣的朋友請繼續關注本站。謝謝!

您可能感興趣的文章:

  • 使用swoole擴展php websocket示例
  • PHP框架Swoole定時器Timer特性分析
  • php異步多線程swoole用法實例
  • php安裝swoole擴展的方法
  • Swoole-1.7.22 版本已發布,修復PHP7相關問題

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved