socket_service.js (node版本)
let ws = require('ws');
let socketServer = ws.Server;
let uuid = require('uuid');
let wss = new socketServer({port:8090})
let User = require('./user.js');
let clients = [];
//广播所有的客户端消息
function broadcastSend(message){
clients.forEach((v,i)=>{
if(v.ws.readState == ws.OPEN){
v.ws.send(JSON.stringify({
"message":message
}))
}
})
}
//开始舰艇端口以及数据
wss.on('connection',function(ws){
let client_uuid = uuid.v4();
clients.push({
"id":client_uuid,
'ws':ws,
});
console.log(`client ${client_uuid} connected`);
//关闭服务
function closeSocket(){
for(var i=0;i<clients.length;i++){
if(clients[i].id == client_uuid){
clients.splice(i,1);
}
}
}
ws.on('message',function(message){
clients.forEach((item)=>{
item.ws.send(message);
})
//broadcastSend(message);
})
ws.on('close',function(){
closeSocket()
})
})
socket_client.js(web版本)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="google" content="notranslate" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script>
window.onload = function(){
var input = document.querySelector('.input');
var btn = document.querySelector('.btn');
var close_btn = document.querySelector('.close');
var ws = new WebSocket("ws://localhost:8090");
ws.onopen = function (e) {
alert('Connection to server opened');
}
var data = 'data';
ws.onmessage = function (data) {
let info = JSON.parse(data.data).msg;
let li = document.createElement('li');
li.innerHTML = info;
document.querySelector('.lists').appendChild(li);
input.value = ''
}
ws.onclose = function () {
alert('closed');
}
btn.onclick = function(){
let val = input.value;
if(!val){alert('消息不能为空!'); return false}
ws.send(JSON.stringify({msg:val}));
}
close_btn.onclick = function(){
ws.onclose = function(){
console.log("Connection closed");
}
}
ws.onerror = function (e) {
alert("connecterror!");
};
}
</script>
</head>
<body>
<ul class="lists"></ul>
<input type="text" class="input" />
<button class="btn">发送</button>
<button class="close">关闭</button>
</body>
</html>
客户端可以同时开始多个页面,都能同时获取到服务端的消息,因为在服务端已经做了循环处理