socket.io with express

2019-03-09 22:14发布

i have a project and I'm using socket.io with express ,

so what i need (i tried) is broadcasting a message but from an express action. is this possible i don't know how to get a reference to send or broadcast.

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

Other things like using both express+socket.io is working with me :)

4条回答
Evening l夕情丶
2楼-- · 2019-03-09 22:24

As long as I understand,

Why not use the socket message type as an event instead of a http get or post? On the client side you would send a message via the websocket with let's say an event property.

So in your case:

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

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

And on the server side:

var io = io.listen(server);

io.on('connection', function (client) {
  client.on('message', function (message) {
    if (message.event == 'homepage loaded') {
      client.broadcast(...);
    }
  });
});
查看更多
够拽才男人
3楼-- · 2019-03-09 22:24

You might want to have a look at my socket.io + Express primer. What you want is covered in detail there.

// 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!');

Where io is the value returned by the call to socketio.listen(). You can place that code anywhere in your application, eg in your app.get callbacks.

查看更多
手持菜刀,她持情操
4楼-- · 2019-03-09 22:28

Check out my example repo where I use ExpressJS + Juggernaut(pubsub over socket.io):

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

This might be overkill for what you need as it uses Publish/Subscribe. But it does, to a certain extent, solve your issue of using regular ExpressJS routes. Checkout the master branch after cloning the repository:

git checkout master

查看更多
可以哭但决不认输i
5楼-- · 2019-03-09 22:28

I Found a nice example how to make what i need but with faye it's here http://nodecasts.org/.

I don't know the difference between Juggernaut ,Faye and direct Socket.io but Faye is good

for my case .And i think both of them use Socket.io internally.

查看更多
登录 后发表回答