1、WebSocket协议是基于tcp协议的一种新型的网络协议。它的实现了浏览器与服务器全双工通信-----允许服务器主动发送信息给客户端
2、http协议通信只能有客户端发送请求
服务端:
$server = new SwooleWebSocketServer("0.0.0.0", 9501); $server->on('open', function (SwooleWebSocketServer $server, $request) { echo "server: handshake success with fd{$request->fd} "; }); $server->on('message', function (SwooleWebSocketServer $server, $frame) { echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish} "; $server->push($frame->fd, "this is server"); }); $server->on('close', function ($ser, $fd) { echo "client {$fd} closed "; }); $server->start();
客户端:
<h1>swooler-websocket测试</h1> <script> var wsurl = "域名:端口号"; var websocket = new WebSocket(weurl); //实例对象onopen属性 websocket.ononnpen = function(evt){ console.log("connected-swoole-connect"); } websocket.onmessage = function (evt){ console.log("server-return-data:"+etv,data); } websocket.onclose = functin(evt){ console.log("close"); } websocket.onerror = function(evt,e){ console.log("server-error"_etv.data); } </script>
优化的代码:
<?php class websocket { CONST PORT = 8812; CONST HOST = 0.0.0.0; public $ws = ''; public function __construct() { $this->ws = new swoole_websocket_server('0.0.0.0',8812);
$this->ws->set([
'work_num'=>2,
'task_worker_num'=>4
]); //可以看swoole文档,websocketserver $this->ws->on("open",[$this,'onOpen']); $this->ws->on('message',[$this,'onMessage']); $this->ws->on('close',[$this,onclose]); $this->ws->on('task',[$this,onTask]); $this->ws->on('finish',[$this,onFinish]); $this->ws->start(); } /* * 监听ws连接事件 */ public function onOpen($ws,$request) { //客户端ID var_dump($request->fd); } public function onMessage($ws,$frame) { echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish} "; $data = [ 'task'=>1, 'frame'=>$frame->fd ]; $ws->task($data); //返回给客户端一个数据 $ws->push($frame->fd, "this is server"); } /* *$task_id是任务ID,由swoole扩展内自动生成,用于区分不同的任务。$task_*id和$src_worker_id组合起来才是全局唯一的,不同的worker进程投递的任ID*可能会有相同 *$src_worker_id来自于哪个worker进程 *$data 是任务的内容, task 任务异步机制,可以用于一个非常耗时的任务,异步执行 */ public function onTask($ws, $task_id, $src_worker_id, $data) { sleep(10); return "task finish"; } /* *$task_id是任务的ID *$data是任务处理的结果内容 *task进程的onTask事件中没有调用finish方法或者return结果,worker进程 *不会触发onFinish *执行onFinish逻辑的worker进程与下发task任务的worker进程是同一个进程 */ public function onFinish($ws, $task_id, $data) { echo "task_id:{$task_id}"; echo "finish_success:{$data}"; } public function onClose($ws,$fd) { echo "client {$fd} closed "; } } $obj = new websocket();