const express = require('express') const app = express() const port = 3000 const fs = require('fs') const { request } = require('http') const url = require('url') const clientHTML = fs.readFileSync('chatClient.html') let clients = [] app.listen(port, () => { console.log(`Example app listening on port ${port}`) }) app.on('request', (request, response) => { let pathname = url.parse(request.url).pathname if (pathname === '/') { response.writeHead(200, { 'Content-Type': 'text/html' }).end(clientHTML) } else if ( pathname !== '/chat' || (request.method !== 'GET' && request.method !== 'post') ) { response.writeHead(404).end() } else if (request.method === 'GET') { acceptNewClient(request, response) } else { broadcastNewMessage(request, response) } }) function acceptNewClient(request, response) { clients.push(response) request.connection.on('end', () => { clients.splice(clients.indexOf(response), 1) response.end() }) response.writeHead(200, { 'Content-Type': 'text/event-stream', Connection: 'keep-alive', 'Cache-Control': 'no-cache', }) response.write('event: chat\ndata: Connected\n\n') } async function broadcastNewMessage(request, response) { request.setEncoding('utf8') let body = '' for (let chunk of request) { body += chunk } response.writeHead(200).end() let message = 'data: ' + body.replace('\n', '\ndata') let event = 'event: chat\n${message}\n\n' clients.forEach((client) => client.write(event)) }
时间: 2023-12-03 13:04:16 浏览: 141
详解express + mock让前后台并行开发
这段代码是一个基于 Express 框架构建的简单聊天室应用程序的后端实现。其中,客户端请求通过监听 `request` 事件来处理。当客户端发起 GET 请求时,会调用 `acceptNewClient` 函数,将客户端的响应对象存储在 `clients` 数组中,并返回一些 SSE(Server-Sent Events)格式的数据,以告知客户端连接已经建立。当客户端发起 POST 请求时,会调用 `broadcastNewMessage` 函数,将客户端发送的消息内容通过 SSE 的形式广播给所有连接的客户端。这里的 SSE 是一种基于 HTTP 的推送技术,可以实现服务器向客户端的单向实时通信。
阅读全文