![](/img/trans.png)
[英]Cannot establish connection between server and client using socket.io with NodeJS, ReactJS and Express
[英]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.