在快速路由文件中使用socket.io [英] Use socket.io inside a express routes file

查看:97
本文介绍了在快速路由文件中使用socket.io的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆