前端代码
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body>
<input type="text">
<button onclick="ksend()">发送请求</button><div></div>
</body>
<script>
var input = document.querySelector('input')
var button = document.querySelector('button')
var div = document.querySelector('div')var socket = new WebSocket('ws://localhost:3000')
const TYPE_ENTER = 0
const TYPE_LEAVE = 1
const TYPE_MSG = 2socket.addEventListener('open',function(){div.innerHTML = "连接成功了<br>"
})function ksend(){var value = input.valuesocket.send(value)input.value = ""
}socket.addEventListener('message',function(e){var data = JSON.parse(e.data)console.log(data.type);var dv = document.createElement('div')dv.innerHTML += data.msg + '-----' + data.timeif(data.type===TYPE_ENTER){dv.style.color = 'green'}else if(data.type===TYPE_LEAVE){dv.style.color = 'red'}div.appendChild(dv)})</script></html>
后端node代码
需要先安装nodejs-websocket模块
const ws = require('nodejs-websocket')
const PORT = 3000
const TYPE_ENTER = 0
const TYPE_LEAVE = 1
const TYPE_MSG = 2let count = 0
const serve = ws.createServer(connect =>{console.log("新的用户连接上来了");count++connect.name = `用户${count}`broadcast({type:TYPE_ENTER,msg:`${connect.name}进入了聊天室`,time:new Date().toLocaleTimeString()})connect.on('text',data=>{broadcast({type:TYPE_MSG,msg:data ,time:new Date().toLocaleTimeString()})})connect.on('close',()=>{console.log('连接断开了');count--broadcast({type:TYPE_LEAVE,msg:`${connect.name}离开了聊天室`,time:new Date().toLocaleTimeString()})})connect.on('error',()=>{console.log("用户连接异常");})
})function broadcast(msg){serve.connections.forEach(item=>{item.send(JSON.stringify(msg))})
}serve.listen(PORT,()=>{console.log("websocket启动成功,端口号"+PORT);})