一、原生的api连接

js客户端

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
44
45
46
47
var ws = null;

//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
ws = new WebSocket("ws://localhost:8888");
} else {
alert('Not support websocket')
}

//连接发生错误的回调方法
ws.onerror = function (event) {
setMessageInnerHTML("websocket client error");
console.log(event);
};

//连接成功建立的回调方法
ws.onopen = function (event) {
setMessageInnerHTML("websocket client open!");
}

//接收到消息的回调方法
ws.onmessage = function (event) {
setMessageInnerHTML('websocket client receive msg:' + event.data);
}

//连接关闭的回调方法
ws.onclose = function () {
setMessageInnerHTML("websocket close!");
console.log('连接关闭');
}

//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
ws.close();
}

//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}

//发送消息
function send() {
var message = document.getElementById('text').value;
ws.send(message);
setMessageInnerHTML('websocket client send msg:' + message);
}

index.html

1
2
3
4
5
6
7
8
9
<body>
Welcome Websocket Client
<br />
<input id="text" type="text" style="width:600px" />
<button onclick="send()">Send message</button>
<button onclick="closeWebSocket()">Close Websocket</button>
<div id="message" style="margin-top: 20px;">
</div>
</body>

node服务端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const WebSocket = require('ws');

const ws = new WebSocket.Server({ port: 8888 });

ws.on('connection', ws => {
console.log('websocket connection succeeded!');

ws.send('hello, client!');

ws.on('open', msg => {
console.log('websocket server open!');
});

ws.on('message', msg => {
console.log('websocket server receive msg:', msg.toString());
});

ws.on('close', msg => {
console.log('websocket client closed!',);
});
});