效果图如下 分别为用户1、2、3的浏览器端页面
简易设计了用户进入聊天室后的总人数为当前用户的名称。
客户端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
</style>
</head>
<body>
<input type="text">
<button>发送</button>
<div></div>
<script>
var input = document.querySelector('input');
var button = document.querySelector('button');
var div = document.querySelector('div');
var socket = new WebSocket('ws://localhost:8000');
socket.addEventListener('open',()=>{
div.innerHTML = '连接到了服务器';
})
button.onclick = function(){
socket.send(input.value);
input.value = '';
}
socket.addEventListener('close',()=>{
div.innerHTML = '服务断开连接'
})
socket.addEventListener('message',(e)=>{
var dv = document.createElement('div');
dv.innerText = e.data;
div.appendChild(dv);
})
</script>
</body>
</html>
服务端代码
var ws = require('nodejs-websocket');
var count = 0;
const server = ws.createServer(conn =>{
console.log('连接已经建立');
count++;
conn.userName = `用户${count}`
broadcast(`${conn.userName}进入了聊天室`,'')
conn.on('text', data => {
console.log('接收到用户数据');
broadcast(data,conn.userName)
})
conn.on('close',()=>{
console.log('用户断开了');
})
conn.on('error',()=>{
console.log('用户异常');
broadcast(`${conn.userName}离开了聊天室`,'')
})
})
function broadcast(msg,userName){
if(userName!=''){
server.connections.forEach(item=>{
item.send(userName+':'+msg)
})
}
else{
server.connections.forEach(item=>{
item.send(msg)
})
}
}
server.listen(8000,()=>{
console.log('服务器已经开启,8000端口监听中');
})
|