现在我有以下代码: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');
};
我怎样才能实现这个目标?提前致谢
最佳答案
要向所有连接的套接字发送套接字消息,您只需调用 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');
}
};
}
更简洁的实现将使您的路由公开套接字代码可以绑定(bind)到的事件。以下未经测试,但应该非常接近。
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();
然后在绑定(bind)快速路由和 socket.io 时在 app.js 文件中。
app.get('/send', routes.index);
routes.on('index', function() {
io.sockets.emit('hello', 'world');
});
还有很多其他方法可以实现这一目标,但最好的方法取决于您想要做什么。正如我之前提到的,向所有人调用广播比向特定用户广播要简单得多。
关于node.js - 在 http 请求上触发 socket.emit(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18004399/