server服务端
<?php
/**
* ws 优化 基础类库
*
*/
class Ws {
CONST HOST = "0.0.0.0";
CONST PORT = 8812;
public $ws = null;
public function __construct() {
$this->ws = new swoole_websocket_server("0.0.0.0", 8812);
$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();
前端javascript
<script type="text/javascript">
function WebSocketTest()
{
if ("WebSocket" in window)
{
alert("您的浏览器支持 WebSocket!");
// 打开一个 web socket
var ws = new WebSocket("ws://localhost:9998/echo");
ws.onopen = function()
{
// Web Socket 已连接上,使用 send() 方法发送数据
ws.send("发送数据");
alert("数据发送中...");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
alert("数据已接收...");
};
ws.onclose = function()
{
// 关闭 websocket
alert("连接已关闭...");
};
}
else
{
// 浏览器不支持 WebSocket
alert("您的浏览器不支持 WebSocket!");
}
}
</script>
网友评论