ChatGPT解决这个技术问题 Extra ChatGPT

How to connect two node.js servers with websockets?

Here's my problem:

I have server A, running node.js and using socket.io for communicating with clients (web browsers). This all is running fine and dandy.

However, now that I have server B, which also needs to connect to server A through websockets, I have hit a wall. None of the node.js websocket clients I've found won't work with the socket.io on the server A.

So, this is the case I'm striving for:

.--------.      .----------.      .----------.
| CLIENT | <--> | SERVER A | <--> | SERVER B |
'--------'      '----------'      '----------'

Client-server A connection is done through socket.io

Now, Server B (running node.js) should connect to server A via websocket (in order to go through port 80). But...

Even the example code in socket.io-client module doesn't work... :/

// Connect to server
var socket = new io.Socket('localhost', {port: 8080});
socket.connect();

// Add a connect listener
socket.on('connect', function(socket) { 
    console.log('Connected.');
});

The code just passes without any errors and execution ends after few seconds.

Update: Code samples

Server (which works just fine) looks like this:

// Load requirements
var http = require('http'),
    io = require('socket.io');

// Create server & socket
var server = http.createServer(function(req, res){

    // Send HTML headers and message
    res.writeHead(404, {'Content-Type': 'text/html'});
    res.end('<h1>Aw, snap! 404</h1>');
});
server.listen(8080);
io = io.listen(server);

// Add a connect listener
io.sockets.on('connection', function(socket) { 

    console.log('Client connected.');

    // Disconnect listener
    socket.on('disconnect', function() {
        console.log('Client disconnected.');
    });
});

Client looks like this

console.log('1');

// Connect to server
var io = require('socket.io-client')
var socket = new io.Socket('localhost', {port: 8080});
socket.connect();

console.log('2');

// Add a connect listener
socket.on('connect', function(socket) { 
    console.log('Connected!');
});

console.log('3');

1, 2 and 3 prints out just fine, no errors, and few seconds later the process just exits

Also, server A doesn't output anything to the log, even though I have the socket.io logging set on "everything".

Do you definitely a websockets client or can you just use plain old sockets?
the node.js websocket clients I've found which ones?
I need to at least emulate websockets since I need to connect to the same server.
I've tried socket.io-client, ws, websocket-node
socket.io-client worked for me and others; I think you should post a [non-]working example that illustrates your issues. Also, try adding process.on('UncaughtException') or some logging along the way; "without any errors" means "didn't look hard enough" : )

B
Bagherani

For future people:
Here is 2 very simple Node.js apps that use socket.io to connect, send and receive messages between each other.

Required package is:

npm install socket.io

Node-App-1 server.js:

var io = require('socket.io').listen(3000);
io.on('connection', function (socket) {
    console.log('connected:', socket.client.id);
    socket.on('serverEvent', function (data) {
        console.log('new message from client:', data);
    });
    setInterval(function () {
        socket.emit('clientEvent', Math.random());
        console.log('message sent to the clients');
    }, 3000);
});

Node-App-2 client.js:

var io = require('socket.io-client');
var socket = io.connect("http://localhost:3000/", {
    reconnection: true
});

socket.on('connect', function () {
    console.log('connected to localhost:3000');
    socket.on('clientEvent', function (data) {
        console.log('message from the server:', data);
        socket.emit('serverEvent', "thanks server! for sending '" + data + "'");
    });
});

c
crappish

Turns out I was using old examples, for some reason, even though I triple checked them. Well, doh.

Also, it turned out that the socket.io-client is broken on latest Node (6.x.x). Managed to find an update from github for it, replaced the files and yay, everything's working!

Edit: Unfortunately I didn't save any links to working examples but after quickly skimming through the code it seems that the only changes were to the client code, which now looks like this:

console.log('1');

// Connect to server
var io = require('socket.io-client')
var socket = io.connect('localhost:8080', {reconnect: true});

console.log('2');

// Add a connect listener
socket.on('connect', function(socket) { 
    console.log('Connected!');
});

console.log('3');

Can you post the new examples or point to them? I am facing the exact same issue that you were facing.
Unfortunately I didn't save any links but I skimmed through the working code and I'll update the difference I found to the answer above.
I also got my code working. In my case I had not specified the port. The code started to work after I added port.
F
Fran

Here is a snippet of code I wrote, it's using socket.io 1.0.6 and socket.io-client 1.0.6. The case is the following:

Server A (Socket.io Client) <---> Server B (Socket.io Server)

Server B (Server):

// Load requirements
var http = require('http'),
io = require('socket.io');

// Create server & socket
var server = http.createServer(function(req, res)
{
  // Send HTML headers and message
  res.writeHead(404, {'Content-Type': 'text/html'});
  res.end('<h1>Aw, snap! 404</h1>');
});
server.listen(8080);
io = io.listen(server);

// Add a connect listener
io.sockets.on('connection', function(socket)
{
  console.log('Client connected.');

  // Disconnect listener
  socket.on('disconnect', function() {
  console.log('Client disconnected.');
  });
});

Server A (Client):

console.log('1');
// Connect to server
var io = require('socket.io-client');
var socket = io.connect('http://localhost:8080', {reconnect: true});

console.log('2');

// Add a connect listener
socket.on('connect', function(socket) { 
  console.log('Connected!');
});

console.log('3');

If I'm using localhost:8080 only on the client server it doesn't connect.