socket.io with express

后端 未结 4 861
借酒劲吻你
借酒劲吻你 2021-02-01 07:44

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 ho

相关标签:
4条回答
  • 2021-02-01 08:04

    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.

    0 讨论(0)
  • 2021-02-01 08:10

    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

    0 讨论(0)
  • 2021-02-01 08:19

    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(...);
        }
      });
    });
    
    0 讨论(0)
  • 2021-02-01 08:20

    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.

    0 讨论(0)
提交回复
热议问题