Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
743 views
in Technique[技术] by (71.8m points)

node.js - Socket.io: Connect from one server to another

I'm trying to make a nodejs(socket.io) server to communicate with another one. So the client emits an event to the 'hub' server and this server emits an event to some second server for processing the action.

I tried to do:

var io_client = require( 'socket.io-client' );

and then,

io_client.connect( "second_server_host" ); 

it seems to work for connection but you can't do anything with this:

debug - set close timeout for client 15988842591410188424
info  - socket error Error: write ECONNABORTED
 at errnoException (net.js:642:11)
 at Socket._write (net.js:459:18)
 at Socket.write (net.js:446:15)

I guess I'm doing it wrong and missing something obvious.

Any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just came across this question, and another just like it with a much better answer.

https://stackoverflow.com/a/14118102/1068746

You can do server to server. The "client" code remains the same as if it was on the browser. Amazing isn't it?

I just tried it myself, and it works fine..

I ran 2 servers - using the same exact code - once on port 3000 as server, and another on port 3001 as client. The code looks like this:

  , io = require('socket.io')
  , ioClient = require('socket.io-client')

   .... 

   if ( app.get('port') == 3000 ){

    io.listen(server).sockets.on('connection', function (socket) {
      socket.on('my other event', function (data) {
        console.log(data);
      });
    });
}else{
    function emitMessage( socket ){
        socket.emit('my other event', { my: 'data' });
        setTimeout(function(){emitMessage(socket)}, 1000);
    }
    var socket = ioClient.connect("http://localhost:3000");
    emitMessage(socket);
}

And if you see on the server side a "{my:data}" print every second, everything works great. Just make sure to run the client (port 3001) after the server (port 3000).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...