socket.io 快递

socket.io with express

提问人:ibmkhd 提问时间:11/4/2010 最后编辑:Leopdibmkhd 更新时间:6/23/2012 访问量:20995

问:

我有一个项目,我正在将 socket.io 与 express 一起使用,

所以我需要的(我试过)是广播一条消息,但来自一个明确的动作。 这可能吗,我不知道如何获得要发送或广播的参考。

app.get('/', function(req, res) {
//i need to send messages from here 
});

其他事情,比如同时使用 express+socket.io 正在与我一起工作:)

node.js websocket socket.io

评论


答:

0赞 Shripad Krishna 11/5/2010 #1

看看我的示例存储库,我在其中使用 ExpressJS + Juggernaut(pubsub over socket.io):

http://github.com/shripadk/express-juggernaut-demo

对于您所需要的东西来说,这可能有点矫枉过正,因为它使用发布/订阅。但它确实在一定程度上解决了你使用常规 ExpressJS 路由的问题。克隆存储库后签出 master 分支:

git checkout master

评论

0赞 ibmkhd 11/5/2010
当我执行“git clone git://github.com/shripadk/express-juggernaut.git”时,我收到此错误:“致命:远程端意外挂断”
0赞 ibmkhd 11/5/2010
你的意思是执行这个命令“git clone git://github.com/shripadk/express-juggernaut-demo.git”,这对我有用,但是当我制作“git checkout master”时,我得到“已经在'master'上”,我忽略了这个并运行演示,我得到了这个
0赞 ibmkhd 11/5/2010
“sys”模块现在称为“util”。它应该有一个类似的接口。节点.js:50 抛出 e;process.nextTick 错误,或第一次刻度时的“error”事件 ^ 错误:在 loadModule (node.js:231:20) 的 resolveModuleFilename (node.js:265:13) 处找不到模块“utils”,在 Object.><anonymous 的 require (node.js:291:14) 处的 Object.anonymous (/home/ibrahim/ws/Lebanon/staTest/express-juggernaut-demo/lib/support/juggernaut/lib/juggernaut/channel.js:2:13) Module._compile处的 (node.js:348:23)。js (node.js:356:12) 在 Module.load (node.js:279:25)
0赞 ibmkhd 11/5/2010
在 loadModule (node.js:251:12) 在 require (node.js:291:14) 在 Object.<anonymous> (/home/ibrahim/ws/Lebanon/staTest/express-juggernaut-demo/lib/support/juggernaut/lib/juggernaut/publish.js:4:15)
0赞 Shripad Krishna 11/5/2010
使用节点 v0.2.4!我猜你在节点 v0.3.0 上!您需要等到所有模块都与 v0.3.0 一起使用才能使用该版本。:)
0赞 ibmkhd 11/6/2010 #2

我找到了一个很好的例子,如何制作我需要的东西,但有了 faye,它就在这里 http://nodecasts.org/

我不知道 Juggernaut 、Faye 和 direct Socket.io 之间的区别,但 Faye 很好

就我而言.我认为他们俩都在内部使用 Socket.io。

评论

1赞 Shripad Krishna 11/6/2010
Faye 在内部不使用 socket.io。它基于贝叶协议。但是,这是个好:)
4赞 Philippe Rathé 11/22/2010 #3

只要我明白,

为什么不使用套接字消息类型作为事件而不是 http get 或 post?在客户端,您将通过 websocket 发送消息,假设有一个事件属性。

因此,就您而言:

<script>
  // Initialize socket.io ...

  // and then
  socket.send({event: 'homepage loaded', foo: 'bar'});
</script>

在服务器端:

var io = io.listen(server);

io.on('connection', function (client) {
  client.on('message', function (message) {
    if (message.event == 'homepage loaded') {
      client.broadcast(...);
    }
  });
});
4赞 Daniel Baulig 11/1/2011 #4

你可能想看看我的 socket.io + Express 入门。你想要什么,那里详细介绍。

// Send to all connected sockets
io.sockets.send('Hello, World!');

// Send to all sockets in a specified room
io.sockets.in('room').send('Hello, Room!');

其中 是调用 返回的值。您可以将该代码放置在应用程序中的任何位置,例如回调中。iosocketio.listen()app.get