如何使用 websocket 连接两个 Node.js 服务器?

发布于 2024-12-26 14:08:17 字数 1876 浏览 1 评论 0原文

这是我的问题:

我有服务器 A,运行 node.js 并使用 socket.io 与客户端(Web 浏览器)通信。这一切都运行得很好。

然而,现在我有了服务器B,它也需要通过websocket连接到服务器A,我就碰壁了。我发现的所有node.js websocket客户端都不能与服务器A上的socket.io一起工作。

所以,这就是我正在努力的情况:

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

客户端-服务器连接是通过socket.io完成

的,服务器B(运行node.js)应该通过websocket连接到服务器A(为了通过端口80)。但是...

即使是 socket.io-client 模块中的示例代码也不起作用...:/

// 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.');
});

代码只是通过而没有任何错误,并且执行在几秒钟后结束。

更新:代码示例

服务器(工作得很好)看起来像这样:

// 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.');
    });
});

客户端看起来像这样

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 和 3 打印得很好,没有错误,几秒钟后进程就退出了

此外,服务器 A 没有输出任何内容日志,即使我将 socket.io 日志设置为“所有”。

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

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

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

发布评论

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

评论(3

蒲公英的约定 2025-01-02 14:08:17

对于未来的人:
这是 2 个非常简单的 Node.js 应用程序,它们使用 socket.io 进行连接、发送和接收彼此之间的消息。

所需包为:

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 + "'");
    });
});

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 + "'");
    });
});
淡笑忘祈一世凡恋 2025-01-02 14:08:17

事实证明,由于某种原因,我正在使用旧的示例,尽管我对它们进行了三次检查。嗯,哦。

此外,事实证明,socket.io-client 在最新的 Node (6.xx) 上已损坏。设法从 github 找到更新,替换文件,耶,一切正常!

编辑:不幸的是,我没有保存任何工作示例的链接,但在快速浏览代码后,似乎唯一的更改是客户端代码,现在看起来像这样:

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

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');
策马西风 2025-01-02 14:08:17

这是我编写的代码片段,它使用 socket.io 1.0.6 和 socket.io-client 1.0.6。情况如下:

服务器A(Socket.io客户端)<--->服务器 B(Socket.io 服务器)

服务器 B(服务器):

// 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.');
  });
});

服务器 A(客户端):

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

如果我仅在客户端服务器上使用 localhost:8080,则不会连接。

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.

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