为什么我使用Socket.IO连接NodeJS服务器(Sails)到另一个NodeJS服务器(Express4)失败?

我正尝试使用socket.io-client将Node.JS(使用Sails.JS编写)应用程序连接到另一个Node.JS服务器(Express4 / Socket.io)。

我的Sails Service app/services/Watcher.js看起来像

 var client = require('../../node_modules/sails/node_modules/socket.io/node_modules/socket.io-client'); // callback of the form function(socket) exports.connect = function(callback) { sails.log.debug("will connect socket to", sails.config.watcher.uri, "with Socket.io-client version", client.version); var socket = client.connect(sails.config.watcher.uri); socket.on('connect', function(){ sails.log.debug("connected"); socket.on('disconnect', function(){ sails.log.debug("Disconnected"); }); socket.on('error', function(err){ sails.log.debug("Could not connect", err); }); callback(socket); }); }; 

这是从config/bootstrap.js调用,如下所示:

 Watcher.connect(function(socket){ sails.log.debug("Connected watcher to relay with socket", socket); }); 

在Express方面,我的服务器relay.js非常简单:

 var app = require('express')(), http = require('http').Server(app), io = require('socket.io').listen(http), port = process.env.RELAY_PORT || 8000; app.get('/', function(req, res) { var response = {message: "some response"}; // to be implemented. res.json(response); }); http.listen(port, function () { console.log("Relay listening on port " + port); }); io.sockets.on('connection', function (socket) { console.log("Connection opened", socket); socket.on('disconnect', function () { console.log("Socket disconnected"); }); }); 

当我运行node relay它会尽职尽责地报告

 Relay listening on port 8000 

当我sails lift我的另一台服务器,它忠实地报告

 will connect socket to http://localhost:8000 with Socket.io-client version 0.9.16 

但我从来没有看到一个实际的连接。

如果我指向一个浏览器在localhost:8000我得到{"message":"some response"} JSON响应我期望。

为什么我的中继服务器不能从我的socker.io-client应用程序接受连接?

这里的问题可能是你试图从Sails中重新使用socket.io-client 。 一般来说,如果你直接在你的项目中require()依赖Sails,那么你的方向是错误的。 在这种情况下, socket.io-clientcachingconfiguration和连接,所以你的require是没有得到一个新的副本。

相反,做

 npm install socket.io-client@~0.9.16 --save 

在你的项目和需要

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

这会给你一个新的套接字客户端的工作,并避免与Sails核心版本的任何冲突。