## JavaScript **1. 启动服务器** ~~~ php bin/mix.php ws:start --host=0.0.0.0 --port=9502 ~~~ **2. 将下面代码另存为一个 HTML 文件,在 Chrome 调试模式的 Console 窗口中调试** ~~~ <html> <head> <title>WebSocket</title> </head> <body> <script> var webSocket = function () { ws = new WebSocket("ws://192.168.1.101:9502/websocket"); ws.onopen = function() { console.log("连接成功"); }; ws.onmessage = function(e) { console.log("收到服务端的消息:" + e.data); }; ws.onclose = function() { console.log("连接关闭"); }; }; webSocket(); </script> </body> </html> ~~~ **3. 开始测试** - 加入房间范例代码测试。 在 Console 窗口中输入: ~~~ ws.send('{"method":"join.room","params":[1012,"小明"],"id":1}'); ~~~ 会收到以下响应: ~~~ 收到服务端的文本消息:{"jsonrpc":"2.0","error":null,"result":{"status":"success"},"id":1} ~~~ - 发送消息给用户范例代码测试。 在 Console 窗口中输入: ~~~ ws.send('{"method":"message.emit","params":["大家好"],"id":2}'); ~~~ 会收到以下响应: ~~~ 收到服务端的文本消息:{"jsonrpc":"2.0","error":null,"result":{"status":"success"},"id":2} 收到服务端的文本消息:{"jsonrpc":"2.0","method":"message.update","params":["大家好","1012"],"id":null} ~~~