客户端:
let ws = new WebSocket("ws://localhost:8181");
ws.onopen = function() {
console.log("client:打开连接");
ws.send("client:hello,服务端");
};
ws.onmessage = function(e) {
console.log("client:接收到服务端的消息 " + e.data);
setTimeout(() => {
ws.close();
}, 5000);
};
ws.onclose = function(params) {
console.log("client:关闭连接");
};
服务器: 需下载第三方包 ws
var WebSocket = require('ws');
var wss = new WebSocket.Server({ port: 8181 });
wss.on('connection', function(ws) {
console.log('server: 收到连接');
ws.on('message', function(message) {
console.log('server: 收到消息', message);
});
ws.send('server: hi,客户端');
});