【问题标题】:How to get the socket object in node.js?如何在 node.js 中获取套接字对象?
【发布时间】:2014-04-08 10:37:30
【问题描述】:

我正在使用 node.js(express)+socket.io 制作一个应用程序,我想知道如何从外部使用作为 io.on('connection',function(socket){... 参数的套接字对象,例如 routes 文件夹中的路由文件

app.js

app.get('/foo/:id?', routes.foo);

路由/foo.js

exports.index = function(req, res){
  //do something with socket such as socket.join()
};

任何想法或提示将不胜感激。

已编辑 我的目标是让访问'/foo/:id?' 的用户加入名为id?' 的socket.io 房间(https://github.com/LearnBoost/socket.io/wiki/Rooms)。 所以我想打电话给socket.join('req.params.id')

exports.index = function(req, res){
  //HERE
};

【问题讨论】:

  • 您可以通过req.connection访问底层Socket
  • @Joe 感谢您的评论。但是Socket 我说的是socket.io 的回调参数。我已经偷看了req.connection 有什么虽然我看不到任何东西与其中的socket.io有关还是我错过了什么?
  • req.connection 是 Node.js socket 对象。不确定 socket.io 有什么可用的,抱歉。

标签: node.js express socket.io


【解决方案1】:

你应该使用express.io

这真的很容易实现,你可以这样做:

exports.index = function(req, res){
  req.io.join(req.params.id); // The client for the request joins to the room with name req.params.id
};

【讨论】:

    猜你喜欢
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 2012-05-18
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 2014-10-01
    • 1970-01-01
    相关资源
    最近更新 更多