3
4 5赞
踩
1.以下代码实现一个webSocket连接,在文本输入框中输入内容,点击发送,通过服务器,返回相同的内容显示在下方。
- 1 <!DOCTYPE html>
- 2 <html lang="en">
- 3 <head>
- 4 <meta charset="UTF-8">
- 5 <title>WebSocket</title>
- 6 </head>
- 7 <body>
- 8 <h1>Echo Test</h1>
- 9 <input type="text" id="sendTxt">
- 10 <button id="sendBtn">发送</button>
- 11 <div id="recv"></div>
- 12 <script type="text/javascript">
- 13 var websocket = new WebSocket("ws://echo.websocket.org/");
- 14 websocket.onopen = function(){
- 15 console.log("websocket open");
- 16 document.getElementById("recv").innerHTML = "Connected";
- 17 }
- 18 websocket.inclose = function(){
- 19 console.log('websocket close');
- 20 }
- 21 websocket.onmessage = function(e){
- 22 console.log(e.data);
- 23 document.getElementById("recv").innerHTML = e.data;
- 24 }
- 25 document.getElementById("sendBtn").onclick = function(){
- 26 var txt = document.getElementById("sendTxt").value;
- 27 websocket.send(txt);
- 28 }
- 29
- 30 </script>
- 31 </body>
- 32 </html>
下面通过Chrom浏览器开发者工具查看相关信息:
(1)点击Network,选中ws栏,注意选中Filter。
(2)刷新页面,可以看到一个ws连接。
(3)点击。
(4)也可以查看输入和发送的信息。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。