企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## WebSocket服务器 示例: ``` class WebSocketServer{ private $serv = null; public function __construct(){ $this->serv = new swoole_websocket_server("0.0.0.0", 9501); $this->serv ->on('open',[$this,'onOpen']); $this->serv->on('message',[$this,'onMessage']); $this->serv->on('close',[$this,'onClose']); $this->serv->start(); } //监听WebSocket连接打开事件 public function onOpen($ws,$request){ var_dump($request->fd, $request->get, $request->server); $ws->push($request->fd, "hello, welcome\n"); } //监听WebSocket消息事件 public function onMessage($ws,$frame){ echo "Message: {$frame->data}\n"; $ws->push($frame->fd, "server: {$frame->data}"); } //监听WebSocket连接关闭事件 public function onClose($ws, $fd){ echo "client-{$fd} is closed\n"; } } new WebSocketServer(); ``` 前端调用示例: ``` ~~~ var wsServer = 'ws://127.0.0.1:9501'; var websocket = new WebSocket(wsServer); websocket.onopen = function (evt) { console.log("Connected to WebSocket server."); }; websocket.onclose = function (evt) { console.log("Disconnected"); }; websocket.onmessage = function (evt) { console.log('Retrieved data from server: ' + evt.data); }; websocket.onerror = function (evt, e) { console.log('Error occured: ' + evt.data); }; ~~~ ```