多人聊天
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>在线聊天</title>
</head>
<body>
<h1>websocket</h1>
<div id="chatroom" style="width: 400px;height: 300px;overflow: auto;border: 1px solid blue;"></div>
<input type="text" name="sayinput" id="sayinput" value="">
<input type="button" name="send" id="sendbutton" value="发送">
<script src="./webClient.js" charset="utf-8"></script>
<script>
function send(){
ws.send(sayinput.value)
sayinput.value = ''
}
document.onkeyup = function(event){
if(event.keyCode ==13){
send()
}
}
sendbutton.onclick = function(){
send()
}
</script>
</body>
</html>
node webServer.js
var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({port:9000})
var clientMap = new Object()
var i = 0
wss.on('connection',function(ws) {
console.log(ws+'上线')
ws.name = ++i
clientMap[ws.name] = ws
ws.on('message',function(message){
broadcast(message,ws)
})
ws.on('close',function(){
console.log('离开')
})
})
function broadcast(msg,ws) {
for(var key in clientMap){
clientMap[key].send(ws.name+'说:' + msg)
}
}
需要引入的webClient.js
var ws = new WebSocket('ws://127.0.0.1:9000/')
// 建立连接时触发
ws.onopen = function() {
// ws.send('大家好')
ws.send('XXXX')
}
// 客户端接收服务端数据时触发
ws.onmessage = function(event) {
var chatroom = document.querySelector("#chatroom");
chatroom.innerHTML += `<br/>` + event.data
}
// 连接关闭时触发
ws.onclose = function() {
alert('closed')
}
// 通信发生错误时触发
ws.onerror = function(err) {
alert('error'+err)
}