繁体   English   中英

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

[英]Why is my connection of a NodeJS server (Sails) to another NodeJS Server (Express4) using Socket.IO failing?

我正在尝试使用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 通常,如果直接在项目中对requires require()依赖Sails进行依赖,那么您将朝着错误的方向前进。 在这种情况下, socket.io-client缓存配置和连接,因此您require获取新副本。

相反,做

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

在您的项目中,并要求

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

这样可以为您提供套接字客户端的全新副本,并且可以避免与Sails核心版本发生任何冲突。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM