如何将Socket.io与Express.JS结合使用(使用Express应用程序生成器) [英] How to use Socket.io combined with Express.JS (using Express application generator)
问题描述
我正在尝试将Socket.io与Express.JS结合使用(使用Express应用程序生成器).
我发现了一些奇怪的做法(在Express 4和express-generator的/bin/www 中使用socket.io.
我的问题是我无法使用路由文件夹中的套接字.
我可以在app.js和bin/www.js文件中使用它们.当我调用路由index.js时,它只会长时间加载网页而不会出现任何错误.
bin/www.js
I'm trying to use Socket.io combined with Express.JS (using Express application generator).
I've found some aswers how to do this (Using socket.io in Express 4 and express-generator's /bin/www).
My problem is that i cannot make use of the sockets inside the routes folder.
I can use them in the app.js and bin/www.js files. When i call the route index.js it just keeps loading the webpage for a long time without giving any errors.
bin/www.js
...
/**
* Create HTTP server.
*/
var server = http.createServer(app);
var io = app.io
io.attach( server );
...
app.js
...
// Express
var app = express();
// Socket.io
var io = socket_io();
app.io = io;
var routes = require('./routes/index')(io);
...
routes/index.js
module.exports = function(io) {
var app = require('express');
var router = app.Router();
io.on('connection', function(socket) {
console.log('User connected');
});
return router;
}
推荐答案
这是一个有关如何在Express上使用Socket.io的简单示例,我在GitHub上可以找到它:
Here is a simple example on how to use Socket.io with Express that I made available on GitHub here:
后端代码是这样的:
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');
请参见 https://github. com/rsp/node-websocket-vs-socket.io/blob/master/si.js
正如您在此处看到的那样,我正在使用以下方式创建快递应用程序:
As you can see here, I am creating the express app with:
var app = require('express')();
然后,我使用以下应用程序使用该应用程序创建一个http服务器:
Then I create an http server with that app with:
var http = require('http').Server(app);
最后,我使用该http服务器创建Socket.io实例:
And finally I use that http server to create the Socket.io instance:
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.
You can see the entire example on GitHub with both backend and frontend code that works. It currently uses Express 4.14.0 and socket.io 1.4.8.
这篇关于如何将Socket.io与Express.JS结合使用(使用Express应用程序生成器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!