🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
>[danger] 使用场景: **前端发送一个比较耗时/不需要立即返回** ![](https://img.kancloud.cn/b0/e5/b0e539337127dbc455824fdf61dcd29e_1049x639.png) >[danger] 简单运用 * **客户端代码** 新建 webSocket.html 粘贴如下代码: ~~~ <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script> // 实例化 webSocket var websocket = new WebSocket('ws://192.168.108.130:9502'); // 客户端与服务器建立连接并完成 回调 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); }; </script> </body> </html> ~~~ * **服务端代码** 新建 webSocket.php 粘贴如下代码: ~~~ <?php // 创建WebSocket Server对象,监听0.0.0.0:9502端口 $ws = new Swoole\WebSocket\Server('0.0.0.0', 9502); // 监听WebSocket连接打开事件 $ws->on('open', function ($ws, $request) { var_dump($request->fd, $request->server); $ws->push($request->fd, "hello, welcome\n"); }); // 监听WebSocket消息事件 $ws->on('message', function ($ws, $frame) { echo "Message: {$frame->data}\n"; $ws->push($frame->fd, "server: {$frame->data}"); }); // 监听WebSocket连接关闭事件 $ws->on('close', function ($ws, $fd) { echo "client-{$fd} is closed\n"; }); // 启动 $ws->start(); ~~~ * **执行效果** 1. 开启服务监听 `php webSocket.php` ![](https://img.kancloud.cn/0f/5d/0f5d7fc4a0165be38d5d571e93d86a87_445x59.png) 2. 浏览器执行 webSocket.html 进行通讯 ``http://192.168.108.130/webSocket.html`` ![](https://img.kancloud.cn/ee/3f/ee3f23990a8a09e0789aa3cdd54fd004_978x271.png)