webSocket
后端
监听服务器: new WebSocket.server({port:30001}, () => {}) , ws.on('connection', (client)=>{})
接收信息: client.on('message', ()=>{})
发送信息: client.send()
监听断开连接 client.on('close)
const webSocket = require('ws');
const ws = new webSocket.Server({port:3000}, ()=> {
console.log('socket start');
})
// 广播:有用户发送广播字样,全体线上用户都会收到相应信息
let clients = [];
ws.on('connection', (client) => {
clients.push(client);
console.log(client);
client.send('连接成功,后端接收到了前端的数据');
client.on('message', (msg)=> {
console.log('前端的数据:' + msg);
// client.send('后端接收到了前端的数据' + msg);
if(msg.indexOf('广播') != -1) {
sendAll()
}
})
client.on('close', () => {
console.log('前端主动关闭连接');
})
})
function sendAll() {
for(let i = 0; i < clients.length; i++) {
clients[i].send('广播广播广播广播广播广播广播广播广播广播');
}
}
前端
连接服务器: ws.onopen()
接收信息: ws.onmessage = ()=>{}
发送信息: ws.send()
断开连接: ws.onclose()
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<input type="text" id="text">
<button onclick="sendServer()">send server</button>
<script>
const ws = new WebSocket('ws://localhost:3000')
ws.onopen = () => {
console.log('服务器已连接');
}
ws.onmessage = (msg, ) => {
// console.log(msg);
console.log('来自服务器的数据:' + msg.data);
}
ws.onclose = () => {
console.log('断开服务器连接');
}
function sendServer() {
var value = document.getElementById('text').value;
console.log(4554);
ws.send(value);
}
</script>
</body>
</html>