How to connect Two Socket.io Node Application usin

2019-03-14 05:48发布

问题:

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 that.

First Node Application

      var express = require('express')
          , http = require('http');

      var app = express();

      app.use(function (req, res) {
         app.use(express.static(__dirname + '/public'));

     });

     var server = http.createServer(app);
     var io = require('socket.io').listen(server);
     server.listen(3000);


     io.sockets.on('connection',function(socket){

      socket.on('eventFiredInClient',function(data){

      socket.emit('secondNodeAppln',data);// i need to get this event in my 2nd node application how can i do this by using socket.io-client

    });

     });

Second Node Application

    var express=require('express');
    var http=require('http');
    var app=express();
    app.configure(function(){
      app.use(express.static(__dirname + '/public'));
    });
    var server = http.createServer(app);
    var serverAddress = '127.0.0.1'; 
    var serverPort = 3000; //first node appln port
    var clientio = require('socket.io-client');
    var socket = clientio.connect(serverAddress , { port: serverPort }); 
    socket.on('connect', function(){ 

       console.log('connected');

    });

    socket.on('disconnect', function(){

       console.log('disconnected');

     });


   var io = require('socket.io').listen(server);

   server.listen(6509);

   //here i need to get the 'secondNodeAppln' event raised in first node application.How can i do this.

回答1:

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.