How to connect Two Socket.io Node Application using Socket.io-client in Node js

前端 未结 1 412
情歌与酒
情歌与酒 2021-02-04 23:05

In my application i need to connect two socket.io node applications.Using socket.io-client we can do like this.But i don\'t know how socket.io-client works and where to include

1条回答
  •  春和景丽
    2021-02-04 23:20

    You need to create a socket.io client in your first app:

    var io        = require('socket.io').listen(server); // this is the socket.io server
    var clientio  = require('socket.io-client');         // this is the socket.io client
    var client    = clientio.connect(...);               // connect to second app
    
    io.sockets.on('connection',function(socket) {
      socket.on('eventFiredInClient',function(data) {
        client.emit('secondNodeAppln', data); // send it to your second app
      });
    });
    

    And in your second app, just listen for those events:

    io.sockets.on('connection', function (socket) {
      socket.on('secondNodeAppln', function(data) {
        ...
      });
    });
    

    There's a bit of a race condition because the code above doesn't wait for a connect event on the client socket before passing events to it.

    EDIT see this gist for a standalone demo. Save the three files to a directory, start the servers:

    node serverserver &
    node clientserver
    

    And open http://localhost:3012 in your browser.

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