一、代码部分
<?php /** * 为什么用WebSocket? * HTTP的通信只能由客户端发起 * * WebSocket 协议是基于TCP的一种新的网络协议。实现了浏览器与服务器全双工通信——允许服务器主动发送信息给客户端。 * * WebSocket 特点: * 1、建立在TCP协议之上 * 2、性能开销下通信高效 * 3、客户端可以与任意服务器通信 * 4、协议标识符ws wss * 5、持久化网络通信协议 */ use SwooleWebSocketServer; $server = new Server("0.0.0.0", 9502); // 连接并完成握手后会回调此函数 $server->on('open', function (SwooleWebSocketServer $server, $request) { echo "server: handshake success with fd {$request->fd} "; }); // 必选 监听ws消息事件 $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();
客户端:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>websocket client</title> </head> <body> <h1>swoole-ws测试</h1> <script> var wsUrl = 'ws://192.168.199.138:9502'; var websocket = new WebSocket(wsUrl); websocket.onopen = function (evt) { console.log("connect success"); websocket.send('hello-swoole'); }; websocket.onmessage = function (evt) { console.log("server return data: " + evt.data); }; websocket.onclose = function (evt) { console.log("connect close"); }; websocket.onerror = function (evt, e) { console.log("error: " + evt.data); } </script> </body> </html>
开启HTTP Server下,通过浏览器url访问
比如: http://192.168.199.138:8888/ws_client.html