服务端代码
const ws = require('nodejs-websocket')
console.log('开始建立连接...')
const session = {}
const log = []
const server = ws.createServer((conn) => {
conn.on('text', (str) => {
console.log('message: ' + str)
const data = JSON.parse(str)
const {type, nickname, message} = data
if (type === 'open') {
session[conn.key] = conn
conn.sendText(JSON.stringify({data: log}))
}
if (type === 'send') {
log.push(data)
Object.values(session).map(m => {
m.sendText(JSON.stringify({data: [data]}))
})
}
})
conn.on('close', (code, reason) => {
console.log('关闭连接')
delete session[conn.key]
})
conn.on('error', (code, reason) => {
console.log('异常关闭')
})
}).listen(8090)
console.log('websocket建立完毕')
客户端代码
<!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>聊天室</title>
</head>
<body>
<div>昵称 <input type="text" id="nickname" /></div>
<div>内容 <input type="text" id="msg" /></div>
<button id="send">发送</button>
<ul id="msgList"></ul>
<script>
const selector = (name) => document.querySelector(name)
const ws = new WebSocket('ws://localhost:8090')
ws.onopen = (e) => {
console.log('连接服务器成功')
const str = JSON.stringify({
type: 'open'
})
ws.send(str)
}
ws.onclose = (e) => {
console.log('服务器关闭')
}
ws.onerror = (e) => {
console.log('连接出错')
}
ws.onmessage = (e) => {
const res = JSON.parse(e.data)
console.log(res)
res.data.map(m => appendLog(m))
}
function appendLog ({nickname, message}) {
const msgList = selector('#msgList')
const msgElme = document.createElement('li')
msgElme.innerHTML = `${nickname}: ${message}`
msgList.appendChild(msgElme)
}
selector('#send').onclick = sendMsg
selector('#msg').onkeydown = (event) => {
if (event.keyCode === 13) {
sendMsg()
}
}
function sendMsg () {
const nickname = selector('#nickname').value.trimStart().trimEnd()
if (!nickname) {
alert('请输入昵称')
return
}
const message = selector('#msg').value
if (ws.readyState === WebSocket.OPEN) {
const str = JSON.stringify({
nickname,
message,
type: 'send'
})
ws.send(str)
}
}
</script>
</body>
</html>