简介
ws一个使用简单,速度极快,稳定的websocket客户端和服务端的Node.js实现。
安装
cnpm i --save ws
服务端
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', ws => {
console.log(`[SERVER] connection()`);
ws.on('message', message => {
console.log(`[SERVER] Received: ${message}`);
ws.send(`ECHO: ${message}`, err => {
if (err) {
console.log(`[SERVER] error: ${err}`);
}
});
});
});
客户端
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WS</title>
</head>
<body>
<script>
// 创建 WebSocket 对象
var ws = new WebSocket('ws://localhost:8080/');
// 连接建立时触发
ws.onopen = function() {
console.log('WebSocket已连接');
// 使用连接发送数据
ws.send('Hello!');
};
// 客户端接收服务端数据时触发
ws.onmessage = function(msg) {
console.log(msg); // MessageEvent {isTrusted: true, data: "ECHO: Hello!" ...}
// 关闭连接
ws.close();
};
// 通信发生错误时触发
ws.onerror = function(e) {
console.log(e);
};
// 连接关闭时触发
ws.onclose = function() {
console.log('WebSocket已关闭');
}
</script>
</body>
</html>