在快速路由文件中使用 socket.io [英] Use socket.io inside a express routes file
问题描述
我正在尝试将 Socket.io 与 Node.js 结合使用,并在路由的逻辑中发送到套接字.
I'm trying to use Socket.io with Node.js and emit to a socket within the logic of a route.
我有一个相当标准的 Express 3 设置,其中一个 server.js 文件位于路由中,然后我有一个 index.js,它位于路由文件夹中,该文件夹导出站点的所有页面/可公开访问的功能.所以它们看起来像:
I have a fairly standard Express 3 setup with a server.js file that sits in the route, and then I have an index.js which sits in a routes folders that exports all the pages/publically accessible functions of the site. So they look like:
exports.index = function (req, res) {
res.render('index', {
title: "Awesome page"
});
};
使用 server.js 中定义的路由,例如:
with the routing defined in server.js like:
app.get('/',routes.index);
我假设我必须在 server.js 中创建 socket.io 对象,因为它需要服务器对象,但是我如何访问该对象并从 index.js 导出函数向它发出?
I'm assuming I have to create the socket.io object in the server.js, since it needs the server object, but how can I access that object and emit to it from the index.js export functions?
推荐答案
您可以将路由文件设置为函数,并在需要该文件时传递 Socket.IO 对象.
You can set up your routes file as a function, and pass the Socket.IO object when requiring the file.
module.exports = function(io) {
var routes = {};
routes.index = function (req, res) {
io.sockets.emit('payload');
res.render('index', {
title: "Awesome page"
});
};
return routes;
};
然后需要这样的路由:
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var routes = require('./routes')(io);
这篇关于在快速路由文件中使用 socket.io的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!