1. webSocketServer.php
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/4/6 * Time: 16:49 */ $server = new swoole_websocket_server('192.168.1.234', 9503); $server->on('open', function (swoole_websocket_server $server, $request) { echo "server: handshake success with fd{$request->fd}\n"; }); $server->on('message', function (swoole_websocket_server $server, $frame) { echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n"; $server->push($frame->fd, "this is server"); }); $server->on('close', function ($ser, $fd) { echo "client {$fd} closed\n"; }); $server->start();
2.webSocketClient.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="messages"></div> <button οnclick="start()">提交</button> </body> </html> <script> var webSocket=new WebSocket('ws://192.168.1.234:9503'); webSocket.onerror = function(event) { alert(event.data); }; //与WebSocket建立连接 webSocket.onopen = function(event) { document.getElementById('messages').innerHTML = '与服务器端建立连接'; }; //处理服务器返回的信息 webSocket.onmessage = function(event) { document.getElementById('messages').innerHTML += '<br />'+ event.data; }; function start() { //向服务器发送请求 webSocket.send('zgw send server'); } </script>