server端代码
var express = require('express');
var WebSocket = require('ws');
var app = express();
app.use(express.static('./'));
var webS = new WebSocket.Server({host:'10.9.22.171',port:8080},()=>{
console.log('success')
});
var clients = [];
var ulist = [];
webS.on('connection',(client)=>{
console.log('连接成功')
clients.push(client);
client.on('message',(msg)=>{
var msg = JSON.parse(msg)
if(msg.text){
for(var i = 0 ; i < clients.length ; i++){
clients[i].send(JSON.stringify(msg));
}
}else{
ulist.push(msg);
for(var i = 0 ; i < clients.length ; i++){
clients[i].send(JSON.stringify(ulist));
}
}
})
client.on('close',()=>{
for(var i = 0 ; i < clients.length ; i++){
if(client == clients[i]){
clients.splice(i,1);
ulist.splice(i,1);
break;
}
}
console.log(ulist);
for(var k = 0 ; k < clients.length ; k++){
clients[k].send(JSON.stringify(ulist));
}
console.log('客户端关闭连接')
})
})
app.listen('8090',()=>{
console.log('app success')
})
客户端代码
<!DOCTYPE html>
<html>
<head>
<title>WebSocket</title>
<style type="text/css">
*{margin:0;padding:0;}
body{background-color:#333;}
main{overflow:hidden;margin:0 auto;width:500px;}
div{overflow:hidden;}
ul,ol{float:left;list-style:none;}
ul{width:400px;height:400px;overflow-y:auto;background-color:#0ff;}
ol{width:100px;height:400px;background-color:#00f;}
li{width:400px;}
li p{width:400px;}
.right{text-align:right;}
p{width:500px;overflow:hidden;}
textarea{width:500px;height:100px;resize:none;border:none;display:block;outline:none;}
button{float:right;width:60px;height:30px;border:none;outline:none;cursor:pointer;}
</style>
</head>
<body>
<main>
<div>
<ul id="lala">
</ul>
<ol id="dede">
</ol>
</div>
<p>
<textarea id="text"></textarea>
<button id="btn">发送</button>
<button id="leave">关闭</button>
</p>
</main>
<script type="text/javascript">
var uname = prompt("请输入用户名");
var ws = new WebSocket("ws://10.9.22.171:8080");
ws.onopen = ()=>{
console.log('连接建立');
ws.send(JSON.stringify({uname}));
ws.onmessage = (msg)=>{
msg = JSON.parse(msg.data);
if(msg.text){
if(msg.uname == uname){
lala.innerHTML += "<li class='right'><h4>"+msg.uname+"</h4><p>"+msg.text+"</p></li>"
}else{
lala.innerHTML += "<li><h4>"+msg.uname+"</h4><p>"+msg.text+"</p></li>"
}
}else{
dede.innerHTML = '';
for(var i = 0 ; i < msg.length ; i++){
dede.innerHTML += '<li>'+msg[i].uname+'</li>';
}
}
}
ws.onclose = ()=>{
console.log('服务端关闭连接')
}
}
btn.onclick = ()=>{
ws.send(JSON.stringify({uname,'text':text.value}));
text.value = '';
}
leave.onclick = ()=>{
window.close();
}
</script>
</body>
</html>