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

发布于 2024-12-29 03:47:54 字数 571 浏览 0 评论 0原文

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

我尝试这样做:

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

然后,

io_client.connect( "second_server_host" ); 

它似乎可以用于连接,但你无法对此做任何事情:

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'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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

滥情空心 2025-01-05 03:47:54

刚刚遇到这个问题,另一个类似的问题有更好的答案。

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

您可以进行服务器到服务器的操作。 “客户端”代码与浏览器上的代码保持相同。很神奇不是吗?

我自己尝试了一下,效果很好。

我运行了 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);
}

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

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

柠檬心 2025-01-05 03:47:54

对于任何寻找简短工作示例的人,请参阅下文。此示例适用于 [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();
    } );
} );

For anyone searching for a short working example, see below. This example works with [email protected] and [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();
    } );
} );
可爱咩 2025-01-05 03:47:54

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

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

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.

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

旧城空念 2025-01-05 03:47:54

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

For anyone looking to do this on a MeteorJS app, I created a new Meteor package joncursi:socket-io-client to solve this problem. Please see https://atmospherejs.com/joncursi/socket-io-client for 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.com without a hitch.

你怎么这么可爱啊 2025-01-05 03:47:54

ECONNABORTED 表示连接已被“另一方”关闭。

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

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

ECONNABORTED means that the connection have been closed by "the other side".

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.

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.

知足的幸福 2025-01-05 03:47:54

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

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

使用 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);

我将使用桥接模式:

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://npmjs.org/package/ws-tcp-bridge

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

希望这有帮助...

干杯

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.

You can weave a tcp strategy into your websocket logic.

Using 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

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

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

Hope this helps...

Cheers

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文