参考:https://blog.csdn.net/linysuccess/article/details/109223712
配合上篇文章,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>WebSocket测试</title> <script> function initWebSocket(wsUri) { var websocket = new WebSocket(wsUri); websocket.onopen = function(evt) { console.log('连接建立中... '+wsUri); }; websocket.onclose = function(evt) { console.log('连接关闭中...', evt); }; websocket.onmessage = function(evt) { console.log('收到来自服务端的消息:', evt.data); }; websocket.onerror = function(evt) { console.log('发生错误...', evt); }; return websocket; } // 在此配置 websocket 的地址 var websocket = initWebSocket("ws://localhost:8020/ws"); var msg, i = 0; var loop = setInterval(function(){ msg = "Hello " + (i++); if(websocket.readyState == WebSocket.OPEN) { websocket.send(msg); console.log('已发送消息:' + msg); } else { clearInterval(loop); console.log('连接已关闭,拜拜~'); } }, 3000); </script> </head> <body> 请按 F12 打开控制台查看消息 </body> </html> |
from:http://www.manongjc.com/detail/22-lipyczhcovoolme.html