下面是一个关于如何将 Socket.io 与 Express 结合使用的简单示例,我在 GitHub 上提供了该示例:
- https://github.com/rsp/node-websocket-vs-socket.io
后端代码是这样的:
var path = require('path');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', (req, res) => {
console.error('express connection');
res.sendFile(path.join(__dirname, 'si.html'));
});
io.on('connection', s => {
console.error('socket.io connection');
for (var t = 0; t < 3; t++)
setTimeout(() => s.emit('message', 'message from server'), 1000*t);
});
http.listen(3002, () => console.error('listening on http://localhost:3002/'));
console.error('socket.io example');
See https://github.com/rsp/node-websocket-vs-socket.io/blob/master/si.js
正如您在这里所看到的,我正在使用以下命令创建 Express 应用程序:
var app = require('express')();
然后我使用该应用程序创建一个 http 服务器:
var http = require('http').Server(app);
最后,我使用该 http 服务器来创建 Socket.io 实例:
var io = require('socket.io')(http);
运行后:
http.listen(3002, () => console.error('listening on http://localhost:3002/'));
一切都协同工作。
您可以在 GitHub 上查看整个示例,其中包含有效的后端和前端代码。目前使用 Express 4.14.0 和 socket.io 1.4.8。