如何使用 websockets 连接两个 node.js 服务器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8837236/
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
How to connect two node.js servers with websockets?
提问by crappish
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.
我有服务器 A,运行 node.js 并使用 socket.io 与客户端(Web 浏览器)通信。这一切都运行良好,花花公子。
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.
但是,现在我有服务器 B,它也需要通过 websockets 连接到服务器 A,我已经碰壁了。我发现的所有 node.js websocket 客户端都不能与服务器 A 上的 socket.io 一起使用。
So, this is the case I'm striving for:
所以,这就是我正在努力的情况:
.--------. .----------. .----------.
| CLIENT | <--> | SERVER A | <--> | SERVER B |
'--------' '----------' '----------'
Client-server A connection is done through socket.io
Client-server 一个连接是通过socket.io完成的
Now, Server B (running node.js) should connect to server A via websocket (in order to go through port 80). But...
现在,服务器 B(运行 node.js)应该通过 websocket 连接到服务器 A(为了通过端口 80)。但...
Even the example code in socket.io-client module doesn't work... :/
甚至 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.');
});
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
1、2 和 3 打印得很好,没有错误,几秒钟后进程就退出了
Also, server A doesn't output anything to the log, even though I have the socket.io logging set on "everything".
此外,服务器 A 不会向日志输出任何内容,即使我在“所有内容”上设置了 socket.io 日志记录。
采纳答案by 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!
此外,事实证明,socket.io-client 在最新的 Node (6.xx) 上被破坏了。设法从 github 上找到了更新,替换了文件,是的,一切正常!
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');
回答by Bagherani
For future people:
Here is 2 very simple Node.jsapps that use socket.ioto connect, send and receive messages between each other.
对于未来的人:
这里有 2 个非常简单的Node.js应用程序,它们使用socket.io在彼此之间连接、发送和接收消息。
Required package is:
所需的包是:
npm install socket.io
Node-App-1 server.js:
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:
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 + "'");
});
});
回答by Regnoult
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:
这是我写的一段代码,它使用 socket.io 1.0.6 和 socket.io-client 1.0.6。案例如下:
Server A (Socket.io Client) <---> Server B (Socket.io Server)
服务器 A(Socket.io 客户端)<---> 服务器 B(Socket.io 服务器)
Server B (Server):
服务器 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.');
});
});
Server A (Client):
服务器 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');
If I'm using localhost:8080 only on the client server it doesn't connect.
如果我仅在客户端服务器上使用 localhost:8080 它不会连接。

