node.js Socket.io:从一台服务器连接到另一台服务器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9018888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:04:28  来源:igfitidea点击:

Socket.io: Connect from one server to another

node.jssocket.io

提问by Sergey V. Pereslavtsev

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.

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

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?

有什么建议?

回答by guy mograbi

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

刚刚遇到这个问题,另一个就像它一样,答案要好得多。

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

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:

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

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

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

回答by Simon A. Eugster

For anyone searching for a short working example,see below. This example works with [email protected]and [email protected].

对于寻找简短工作示例的任何人请参见下文。此示例适用于[email protected][email protected]

var port = 3011;

var server = require( 'http' ).createServer( ).listen( port, function () {
    console.log( "Express server listening on port " + port );
} );

var io = require( 'socket.io' ).listen( server ).set( "log level", 0 );

io.sockets.on( "connection", function ( socket ) {
    console.log( 'Server: Incoming connection.' );
    socket.on( "echo", function ( msg, callback ) {
        callback( msg );
    } );
} );


var ioc = require( 'socket.io-client' );
var client = ioc.connect( "http://localhost:" + port );

client.once( "connect", function () {
    console.log( 'Client: Connected to port ' + port );

    client.emit( "echo", "Hello World", function ( message ) {
        console.log( 'Echo received: ', message );
        client.disconnect();
        server.close();
    } );
} );

回答by Dragunov

For Server to Server or App to App communication, I think you should look into Redis Pub-sub. Its capable of very good speeds, and can handle the entire message queuing architecture of a big app.

对于 Server to Server 或 App to App 通信,我认为您应该查看 Redis Pub-sub。它具有非常好的速度,并且可以处理大型应用程序的整个消息队列架构。

Here is a slightly complex but quite understandable example for using Redis Pub Sub: Redis Pub Sub Example

这是一个使用 Redis Pub Sub 的稍微复杂但很容易理解的示例: Redis Pub Sub Example

回答by Cody

The native Node TCP module is probably what you want - I wanted to do what you're trying to do but it seems that the fact that WebSockets are strictly many-browser to server, or browser to many-server.

本机 Node TCP 模块可能就是您想要的 - 我想做您想做的事情,但 WebSockets 似乎是严格的多浏览器到服务器,或浏览器到多服务器的事实。

You can weave a tcp strategy into your websocket logic.

您可以将 tcp 策略编织到您的 websocket 逻辑中。

Using tcp:

使用 tcp:

var net = require('net');
var tcp = net.connect({port: 3000, host: 'localhost'});
tcp.on('connect', function(){
  var buffer = new Buffer(16).fill(0);
  buffer.write('some stuff');
  tcp.write(buffer);
});

tcp.on('data', function(data){console.log('data is:', data)});
tcp.on('end', cb);
tcp.on('error', cb);

I would use a bridge pattern with this:

我会使用桥接模式:

https://www.google.com/search?q=javascript+bridge+pattern&aq=f&oq=javascript+bridge+pattern&aqs=chrome.0.57.6617&sourceid=chrome&ie=UTF-8

https://www.google.com/search?q=javascript+bridge+pattern&aq=f&oq=javascript+bridge+pattern&aqs=chrome.0.57.6617&sourceid=chrome&ie=UTF-8

OR, use the Node Module https://npmjs.org/package/ws-tcp-bridge

或者,使用节点模块https://npmjs.org/package/ws-tcp-bridge

I also heard that using redis can be quite helpful - Socket.io uses this as a fallback.

我还听说使用 redis 会很有帮助 - Socket.io 使用它作为后备。

Hope this helps...

希望这可以帮助...

Cheers

干杯

回答by Some programmer dude

ECONNABORTEDmeans that the connection have been closed by "the other side".

ECONNABORTED意味着连接已被“另一边”关闭。

For example, lets say we have two programs, A and B. Program A connects to program B, and they start to send data back and forth. Program B closes the connection for some reason. After the connection was closed program A tries to write to program B, but since the connection is closed program A will get the error ECONNABORTED.

例如,假设我们有两个程序,A 和 B。程序 A 连接到程序 B,它们开始来回发送数据。程序 B 出于某种原因关闭了连接。连接关闭后,程序 A 尝试写入程序 B,但由于连接已关闭,程序 A 将收到错误ECONNABORTED

One of your programs have closed the connection, and the other doesn't know about it and tries to write to the socket, resulting in an error.

您的一个程序关闭了连接,另一个程序不知道它并尝试写入套接字,从而导致错误。

回答by Jon Cursi

For anyone looking to do this on a MeteorJSapp, I created a new Meteor package joncursi:socket-io-clientto solve this problem. Please see https://atmospherejs.com/joncursi/socket-io-clientfor more detail and example usage. Since I've bundled the NPM binaries into a package for you, you don't have to worry about installing NPM packages, declaring NPM.require()dependencies, etc. And best of all, you can deploy to .meteor.comwithout a hitch.

对于希望在MeteorJS应用程序上执行此操作的任何人,我创建了一个新的 Meteor 包joncursi:socket-io-client来解决此问题。有关更多详细信息和示例用法,请参阅https://atmospherejs.com/joncursi/socket-io-client。由于我已为您将 NPM 二进制文件捆绑到一个包中,因此您不必担心安装 NPM 包、声明NPM.require()依赖项等。最重要的是,您可以.meteor.com毫不费力地进行部署。