在我們實際開發過程中,有些數據需要實時獲取;比如erp系統中的訂單信息,OA系統中的流程審批等都需要及時處理,這時我們就不能再使用http協議了;當然也可以使用輪詢的機制。但是輪詢請求中有大半是無用,浪費帶寬和服務器資源。
這時我們就得使用websocket協議來滿足這種業務需求;
準備工作:安裝PHP-swoole拓展;
直接貼代碼;
<?php
new class
{
private $_serv = null;
public function __construct()
{
$this->_serv = new swoole_websocket_server('0.0.0.0', 6552);
$this->_serv->set(array(
'worker_num' => 2,
'dispatch_mode' => 3,
'log_file' => 'swoole.log',
));
//增加個監聽端口
$udpworker = $this->_serv->listen("127.0.0.1", 6553, SWOOLE_SOCK_UDP);
$udpworker->on('Packet', function ($serv, $data, $addr) {
$data = json_decode($data, true);
if(!empty($data)){
//你的業務邏輯
}
});
$this->_serv->on('open', array($this, 'onStart'));
$this->_serv->on('message', array($this, 'onMessage'));
$this->_serv->on('close', array($this, 'onClose'));
$this->_serv->start();
}
public function onStart($serv, $request)
{
echo "server: connect success with fd {$request->fd}\n";
}
//format:'{"school_class_id":"1","school_id":"2"}'
public function onMessage($serv, $frame)
{
/**start*你的業務邏輯***/
}
public function onClose($serv, $fd)
{
echo "client {$fd} closed\n";
}
}
?>
原理:首先創建websocket服務器對象,監聽0.0.0.0:6552端口,然後在用服務對象去監聽UDP 6553的端口。客戶端消息發送到6553藉口,然後在通過6552端口發送給用戶。
以上內容希望幫助到大家,更多PHP大廠PDF面試文檔,PHP進階架構視頻資料,PHP精彩好文免費獲取可以微信搜索關注公衆號:PHP開源社區,或者訪問: