选择开发语言和框架
- Node.js + Express:适合快速开发,文档丰富。
- Python + Flask:轻量级,适合微服务架构。
- Java + Spring Boot:内置支持,适合大型项目。
- PHP + Laravel:功能强大,开发体验好。
- Ruby + Sinatra:适合小项目,快速开发。
安装所需依赖
- Node.js:
npm install express
- Python:
pip install flask
- Java:
// 项目依赖中添加Spring Boot
- PHP:
composer require Laravel
- Ruby:
gem install sinatra
创建简单的SSR服务器
-
Node.js(Express):
const express = require('express'); const app = express(); app.get('/events', function(req, res) { res.setHeader('Content-Type', 'text/event-stream'); setInterval(() => { res.write(`data: ${Math.random().toString(36)}\n`); }, 100); }); app.listen(300, () => { console.log('Server running at http://localhost:300'); }); -
Python(Flask):
from flask import Flask, Response app = Flask(__name__) @app.route('/events') def events(): return Response( 'data: {}\n'.format(str(i)) + '\n', mimetype='text/event-stream' ) with app: i = 0 while True: sleep(1) yield from app.sleep(1) i += 1
编写客户端代码
- JavaScript:
const eventSource = new EventSource('http://localhost:300/events'); eventSource.onmessage = function(e) { console.log('收到数据:', e.data); };
测试服务器配置
- 使用curl:
curl -v http://localhost:300/events
- 使用浏览器:
打开
http://localhost:300/events,检查连接状态。
实现双向通信
-
Node.js:
const express = require('express'); const app = express(); app.get('/events', function(req, res) { res.setHeader('Content-Type', 'text/event-stream'); res.on('close', () => { console.log('客户端断开'); }); req.on('data', (chunk) => { console.log('收到客户端数据:', chunk); res.write(`data: ${chunk}\n`); }); }); app.listen(300, () => { console.log('Server running at http://localhost:300'); });
优化性能
-
数据压缩:
res.writeHead(200, {'Content-Type': 'text/event-stream'}); res.set('Content-Encoding', 'gzip'); res.write('data: ' + data + '\n'); res.end(); -
分割传输:
const split = []; let chunks = []; const size = 1024; app.get('/events', function(req, res) { const encode = (chunk) => chunk.length === 0 ? undefined : 'data: ' + encodeURIComponent(chunk) + '\n'; const send = (data, done) => { const chunk = data.slice(, size); if (chunk.length === 0) done(); split.push(chunk); res.write(encode(chunk)); setTimeout(done, 100); }; req.on('data', (buffer) => { chunks.push(buffer); while (chunks.length > 0) { const chunk = chunks.shift(); send(chunk, () => { chunks = chunks.slice(1); }); } }); res.on('close', () => { while (split.length > 0) { const chunk = split.shift(); console.log('发送完成:', chunk.length); } }); });
获取更多资源
- 文档:MDN Web Docs
- 教程:freeCodeCamp
- 社区:Stack Overflow
通过以上步骤,你可以成功配置并实现SSR,实现服务器对客户端的实时数据推送。









