1:先创建服务端文件WebSocket.php
<?php class WebSocket { private $ws = null; public function __construct(){ //创建WebSocket Server对象,监听0.0.0.0:9502端口 $this -> ws = new Swoole\WebSocket\Server('0.0.0.0', 9502, SWOOLE_PROCESS, SWOOLE_SOCK_TCP | SWOOLE_SSL); $this -> ws->set( [ 'ssl_cert_file' => '__DIR__fullchain.pem',//证书位置 'ssl_key_file' => '__DIR__privkey.pem',//证书位置 // 'open_http2_protocol' => true, ] ); //监听WebSocket连接打开事件 $this -> ws ->on('Open', [$this, "onOpen"]); //监听WebSocket消息事件 $this -> ws->on('Message', [$this, "onMessage"]); //监听WebSocket连接关闭事件 $this -> ws->on('Close', [$this, "onClose"]); $this -> ws->start(); } public function onOpen($ws, $request){ var_dump($request->fd, $request->get, $request->server); $ws->push($request->fd, "欢迎客户端: {$request -> fd}\n"); } public function onMessage($ws, $frame){ echo "信息: {$frame->data}\n"; foreach ($ws -> connections as $fd){ if($fd == $frame -> fd){ $ws->push($fd, "我: {$frame->data}"); }else { $ws->push($fd, "对方: {$frame->data}"); } } } public function onClose($ws, $fd){ echo "客户端:{$fd} 关闭\n"; } } new WebSocket();
2:创建客户端文件demo.php
<!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> <div id="welcome"></div> <div> <input type="text" id="input" /> <input type="button" onclick="send()" value="发送"/> </div> <div id="message"></div> <script src="./jquery.js"></script> <script> var wsServer = "wss://url:9502";//域名加端口 var websocket = new WebSocket(wsServer); console.log(websocket); websocket.onopen = function (res) { $("#welcome").append( "<h1>链接成功,欢迎!</h1>" ); }; websocket.onclose = function (res) { $("#message").append( "<h3>链接关闭</h3>" ); }; websocket.onmessage = function (res) { $("#message").append( "<h3>" + res.data + "<h3>" ); }; websocket.onerror = function (res, e) { $("#message").append( "<h3>" + res.data + "<h3>" ); }; function send(){ websocket.send($("#input").val()); } </script> </body> </html>
3:启动服务php WebSocket.php
最后再补充 端口一定要开启