php websocket 帧封装,swoole websocket封装类和调用
上代碼 ws.php
/**
* ws 優化 基礎類庫
* User: singwa
* Date: 18/3/2
* Time: 上午12:34
*/
class Ws {
CONST HOST = "0.0.0.0";
CONST PORT = 9512;
public $ws = null;
public function __construct() {
$this->ws = new swoole_websocket_server("0.0.0.0", 9512);
$this->ws->set(
[
'worker_num' => 2,
'task_worker_num' => 2,
]
);
$this->ws->on("open", [$this, 'onOpen']);
$this->ws->on("message", [$this, 'onMessage']);
$this->ws->on("task", [$this, 'onTask']);
$this->ws->on("finish", [$this, 'onFinish']);
$this->ws->on("close", [$this, 'onClose']);
$this->ws->start();
}
/**
* 監聽ws連接事件
* @param $ws
* @param $request
*/
public function onOpen($ws, $request) {
var_dump($request->fd);
if($request->fd == 1) {
// 每2秒執行
swoole_timer_tick(2000, function($timer_id){
echo "2s: timerId:{$timer_id}\n";
});
}
}
/**
* 監聽ws消息事件
* @param $ws
* @param $frame
*/
public function onMessage($ws, $frame) {
echo "ser-push-message:{$frame->data}\n";
// todo 10s
$data = [
'task' => 1,
'fd' => $frame->fd,
];
//$ws->task($data);
swoole_timer_after(5000, function() use($ws, $frame) {
echo "5s-after\n";
$ws->push($frame->fd, "server-time-after:");
});
$ws->push($frame->fd, "server-push:".date("Y-m-d H:i:s"));
}
/**
* @param $serv
* @param $taskId
* @param $workerId
* @param $data
*/
public function onTask($serv, $taskId, $workerId, $data) {
print_r($data);
// 耗時場景 10s
sleep(10);
return "on task finish"; // 告訴worker
}
/**
* @param $serv
* @param $taskId
* @param $data
*/
public function onFinish($serv, $taskId, $data) {
echo "taskId:{$taskId}\n";
echo "finish-data-sucess:{$data}\n";
}
/**
* close
* @param $ws
* @param $fd
*/
public function onClose($ws, $fd) {
echo "clientid:{$fd}\n";
}
}
$obj = new Ws();
前端代碼 ws_client.html
dahai-swoole-ws測試
var wsUrl = "ws://192.168.244.132:9512";
var websocket = new WebSocket(wsUrl);
//實例對象的onopen屬性
websocket.onopen = function(evt) {
websocket.send("hello-sinwa");
console.log("conected-swoole-success");
}
// 實例化 onmessage
websocket.onmessage = function(evt) {
console.log("ws-server-return-data:" + evt.data);
}
//onclose
websocket.onclose = function(evt) {
console.log("close");
}
//onerror
websocket.onerror = function(evt, e) {
console.log("error:" + evt.data);
}
結果
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的php websocket 帧封装,swoole websocket封装类和调用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微软黑屏补丁_慎装微软最新Win7补丁
- 下一篇: 动态规划算法php,php算法学习之动态