利用SSE打造极简web聊天室
创始人
2024-11-15 17:12:18
0

在B/S场景中,通常我们前端主动访问后端可以使用axios,效果很理想,而后端要访问前端则不能这样操作了,可以考虑SSE、websocket和gRPC等方式,实时和性能均有保障。
下面给出一个简单的例子,后端是node+express,前端是html+javascript(jquery+axios) 实现一个简单的web聊天室。
不说废话,直接上代码:

const stringRandom = require("string-random");  const express = require('express'); const app = express();  var msgs=[]; var clients=[];  app.use('/', express.static('./'));  app.get('/events', (req,res)=>{ 	res.writeHead(200,  { 'Content-Type': 'text/event-stream', 'Connection': 'keep-alive', 'Cache-Control': 'no-cache' }); 	res.write(`data: ${JSON.stringify(msgs)}\n\n`); 	let clientid=stringRandom(32, { letters: 'ABCDEF' }) 	clients.push({ "clientid":clientid, "res":res }); 	req.on('close', () => { clients = clients.filter(item => (item.clientid != clientid)); }); });  app.post('/sendmsg',express.json(), (req,res)=>{ 	msgs.push(req.body); 	res.json({"code":200}); 	clients.forEach(client=>{ client.res.write(`data: ${JSON.stringify(req.body)}\n\n`)  }); });  app.listen(3000, () => { console.log(`极简聊天室服务启动`); }) 
   极简聊天室       

浏览器访问效果如下:
在这里插入图片描述
在这里插入图片描述

相关内容

热门资讯

透视软件“wepoker的辅助... 透视软件“wepoker的辅助器”We poker辅助器下载(透视)私局辅助(切实有挂)1、We p...
透视中牌率“steampoke... 透视中牌率“steampokermaster辅助”哈糖大菠萝有挂吗(透视)技巧教程(果然存在有挂)1...
透视app!德普之星透视辅助(... 透视app!德普之星透视辅助(透视)透视软件免费入口官网(有挂详情)1、许多玩家不知道德普之星透视辅...
透视肯定!aapoker真的假... 透视肯定!aapoker真的假的(透视)aapoker怎么设置抽水,可靠教程(有挂技巧)1)aapo...
透视讲解“wepoker高级辅... 透视讲解“wepoker高级辅助”wepoker透视脚本免费(透视)辅助器免费安装(本来是真的有挂)...
透视挂透视“cloudpoke... 透视挂透视“cloudpoker外挂”智星德州插件2024最新版(透视)透牌教程(果然是有挂)1、完...
透视辅助!aapoker怎么拿... 透视辅助!aapoker怎么拿好牌(透视)aapoker辅助插件工具,微扑克教程(有挂教程);1、a...
透视玄学!德扑圈有透视吗(透视... 透视玄学!德扑圈有透视吗(透视)透视软件免费入口官网(有挂辅助)1、玩家可以在德扑圈有透视吗软件透明...
透视ai“wepoker有透视... 透视ai“wepoker有透视功能吗”we-poker有人玩吗(透视)有脚本(一贯真的是有挂);1、...
透视私人局“uupoker有透... 透视私人局“uupoker有透视吗”pokemmo辅助工具(透视)线上教程(确实真的有挂)1、在po...