阅读量:0
我们知道WebSocket是可以双向通信的,把极简聊天室代码又改了一下,前端发信息到后端也使用websocket,其实代码量更少了。。。
const express = require('express'); const app = express(); var wsServer = require('express-ws')(app) var msgs=[]; app.use('/', express.static('./')); app.ws('/ws', (ws,req)=>{ ws.send(JSON.stringify(msgs)); ws.on('message', msg => { msgs.push(JSON.parse(msg)); wsServer.getWss().clients.forEach(client=>{ client.send(msg) }); }) }); app.listen(3000, () => { console.log(`极简聊天室WebSocket版服务启动`); })
<!DOCTYPE html> <html> <head> <title>极简聊天室websocket版</title> <meta charset="utf-8"> <script src="jquery-3.6.1.min.js"></script> </head> <body> <input id="msg"></input><button id="send" onclick=sendmsg()>发送</button> <ul id="msgs"> </ul> <script> var uid; let reg = new RegExp("(^|&)" + "uid" + "=([^&]*)(&|$)","i"); let r = location.search.substr(1).match(reg); uid=(r!=null)?decodeURI(r[2]):"me"; var ws = new WebSocket("http://localhost:3000/ws"); ws.onmessage = event => { let jvar=JSON.parse(event.data); if (jvar instanceof Array) { jvar.forEach(item=>{ $("#msgs").append(`<li>${item.uid} 说: ${item.msg}</li>`) }) } else { $("#msgs").append(`<li>${jvar.uid} 说: ${jvar.msg}</li>`) } } function sendmsg() { ws.send(JSON.stringify({"uid":uid,"msg":$("#msg").val()})) } </script> </body> </html>
效果跟前面一样,就不再贴图了。