guozewei0 2020-03-06
将代码复制,存到一个html文件中,打开即可。代码示例:
<html> <head> <meta http-equiv="Content-Type" content="text/html;charset=gbk" /> <title>Web sockets test</title> <script type="text/javascript"> var ws; function Clicked() { try { ws = new WebSocket("ws:http://127.0.0.1:8080/SZYJ/getmoduleinfo?appid=1&ticket=wanli_127.0.0.1_1572340419452");//连接服务器 //ws = new WebSocket("ws://echo.websocket.org/");//连接服务器 //连接websocket ws.onopen = function(event, AlarmMessage) { alert("已经与服务器建立了连接rn当前连接状态:" + this.readyState); }; //websocket传输数据 ws.onmessage = function(event) { alert("接收到服务器发送的数据:rn" + event.data); var bjts = event.data; }; //websocket关闭连接 ws.onclose = function(event) { alert("已经与服务器断开连接rn当前连接状态:" + this.readyState); }; //websocket连接异常 ws.onerror = function(event) { alert("WebSocket异常!"); }; } catch (ex) { alert(ex.message); } }; function seestate() { alert(ws.readyState); } </script> </head> <body> <button id=‘ToggleConnection‘ type="button" onclick=‘Clicked();‘>连接服务器</button> <br /> <br /> <button id=‘ToggleConnection‘ type="button" onclick=‘seestate();‘>查看状态</button> <br /> <br /> </body> </html>
宁玉哥模板: