1.以下代码实现一个webSocket连接,在文本输入框中输入内容,点击发送,通过服务器,返回相同的内容显示在下方。
1
2
3
4
5
WebSocket6
7
8
Echo Test
9
10 发送
11
12
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
31
32
下面通过Chrom浏览器开发者工具查看相关信息:
(1)点击Network,选中ws栏,注意选中Filter。
(2)刷新页面,可以看到一个ws连接。
(3)点击。
(4)也可以查看输入和发送的信息。