Swoole WebSocket服务
什么是websockt?
- 什么是websockt?
- Swoole WebSocket服务
-
- 服务端示例
- 前端示例
- 应用
-
- 1 运行程序
- 2 预览
- 3 代码优化
websocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信—— 允许服务器主动发送信息给客户端。
为什么需要websocket
缺陷:HTTP的同学只能有客户端发起
WebSocket 特点
建立在TCP协议之上 性能开销小通信高效 客户端可以与任意服务器通信 协议标识符ws wss 持久化网络通信协议
Swoole WebSocket服务 服务端示例t.php
print_r($request->fd.'_打开的连接'); echo PHP_EOL; } // 监听ws消息事件 $server->on('message', function (Swoole\WebSocket\Server $server, $frame) { echo "收到连接_{$frame->fd}发送的信息:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n"; $server->push($frame->fd, "后台返回给前台的信息:willem-push-sucsess"); }); $server->on('close', function ($ser, $fd) { echo "client {$fd} closed\n"; }); $server->start();
文件位置在linux的项目根目录。
前端示例t.html
websocket.send("发送 hello-willem"); console.log("conected-swoole-success"); } //实例化 onmessage websocket.onmessage=function(evt){ alert(evt.data+":接收到后端发来的信息弹窗"); 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); } 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",8818); $this->ws->on("open",[$this,"onOpen"]); $this->ws->on("message",[$this,"onMessage"]); $this->ws->on("close",[$this,"onClose"]); $this->ws->start(); } # 监听ws连接事件 public function onOpen($ws,$request){ var_dump($request->fd); } # 监听ws消息事件 public function onMessage($ws,$frame){ echo "收到连接_{$frame->fd}发送的信息:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n"; $ws->push($frame->fd, "后台返回给前台的信息:willem-push-sucsess".date("Y-m-d H:i:s")); } # close public function onClose($ws,$fd){ echo "client:{$fd}\n"; } } $obj=new Ws();