2

现在我有以下代码:foo

sIo.sockets.on('connection', function(socket){
  socket.emit('hello', 'world');
});

当有人从我的路线打开页面时,我希望能够发出这个,如下所示:

//app.js
app.get('/send', routes.index);

//routes.js
exports.index = function(req, res){
  socket.emit('hello', 'world');
};

我怎样才能做到这一点?提前致谢

4

1 回答 1

4

要将套接字消息发送到所有连接的套接字,您只需调用io.sockets.emit而不是 socket.emit。有几种使用 socket.io 发送消息的方法,我将在下面概述。

// Send the message to all connected clients
io.sockets.emit('message', data);

// Send the message to only this client
socket.emit('message', data);

// Send the messages to all clients, except this one.
socket.broadcast.emit('message', data);

还有一个房间的概念,您可以使用它来细分您的客户。

// Have a client join a room.
socket.join('room')

// Send a message to all users in a particular room
io.sockets.in('room').emit('message', data);

所有这些都涵盖了如何发送消息,但现在很明显,您正在询问如何从单独的文件中访问套接字和/或 io 对象。一个选项只是让您将这些依赖项传递给指定的文件。你的 require 行最终会看起来像这样。

var routes = require('./routes')(io);

其中 io 是从 .listen 创建的 socket.io 对象。要在路由文件中处理它,您必须更改定义导出的方式。

module.exports = function(io) {
  return {
    index: function(req, res) {
      io.sockets.emit('hello', 'world');
      res.send('hello world');
    }
  };
}

更简洁的实现会让您的路由公开您的套接字代码可以绑定到的事件。以下内容未经测试,但应该非常接近。

var util = require("util"),
    events = require("events");

function MyRoute() {
  events.EventEmitter.call(this);
}

util.inherits(MyRoute, events.EventEmitter);

MyRoute.prototype.index = function(req, res) {
  this.emit('index');
  res.send('hello world');
}

module.exports = new MyRoute();

然后在你绑定快速路由和 socket.io 时在你的 app.js 文件中。

app.get('/send', routes.index);

routes.on('index', function() {
  io.sockets.emit('hello', 'world');
});

有许多其他方法可以实现这一点,但最好的方法取决于你想要做什么。正如我之前提到的,向所有人发起广播要比向特定用户广播要简单得多。

于 2013-08-01T22:05:52.593 回答