Socket.io:从一台服务器连接到另一台服务器 [英] Socket.io: Connect from one server to another

查看:99
本文介绍了Socket.io:从一台服务器连接到另一台服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个 nodejs(socket.io) 服务器来与另一个服务器进行通信.因此,客户端向集线器"服务器发出一个事件,该服务器向另一台服务器发出一个事件以处理该操作.

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.

我尝试这样做:

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

然后,

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.

有什么建议吗?

推荐答案

刚遇到这个问题,另一个和它一样的答案更好.

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

我运行了 2 个服务器 - 使用完全相同的代码 - 一次在端口 3000 上作为服务器,另一个在端口 3001 上作为客户端.代码如下所示:

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

如果您在服务器端看到每秒打印一次{my:data}",则一切正常.只需确保在服务器(端口 3000)之后运行客户端(端口 3001).

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

这篇关于Socket.io:从一台服务器连接到另一台服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆