官网:ws
npm i ws -D
// server.js
let WebSocket = require('ws');
let instance = new WebSocket.Server({
host: 'localhost',
port: 3000
})
instance.on('connection', client => {
client.on('message', data => {
client.send('收到!');
})
})
客户端
let webclient = new WebSocket('ws://loaclhost:3000');
// 发送消息
btn.onclick = function(){
webclient.send('hello World, hi WebSocket')
}
// 接受消息
webclient.onmessage = function(message){
console.log(message); // 打印 收到!
}
网友评论