如何在Node js中使用Socket.io-client连接两个Socket.io节点应用程序

时间:2013-05-02 05:36:57

标签: node.js express socket.io

在我的应用程序中,我需要连接两个socket.io节点应用程序。使用socket.io-client我们可以这样做。但我不知道socket.io-client如何工作以及在哪里包含它。

第一个节点应用程序

      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

    });

     });

第二节点应用程序

    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 个答案:

答案 0 :(得分:2)

您需要在第一个应用中创建一个socket.io客户端:

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
  });
});

在你的第二个应用程序中,只需听取这些事件:

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

有一些竞争条件,因为上面的代码在将事件传递给它之前不等待客户端套接字上的connect事件。

编辑有关独立演示,请参阅this gist。将这三个文件保存到目录中,启动服务器:

node serverserver &
node clientserver

在浏览器中打开http://localhost:3012