无法获取 socket.io 和 nodejs 运行 OpenShift

Can't get socket.io and nodejs running with OpenShift

我无法在 OpenShift 上获得 socket.io 运行ning。我现在用谷歌搜索了几个小时,但没有任何帮助。在本地它工作正常(当然有不同的端口和本地主机作为主机)。

这是我的 server.js 文件:

var port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var ipadr = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var http = require('http').createServer(function(request, response) {   
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.end();
}).listen(port,ipadr);
console.log(port+":"+ipadr);

var io = require('socket.io').listen(http),
fs = require('fs'),
request = require('request'),
mysql = require('mysql'),
moment = require('moment'),
connectionsArray = [],
connection = mysql.createConnection({
host: 'xxx',
user: 'xxx',
password: 'xxx',
database: 'xxx',
port: 3306
}),
POLLING_INTERVAL = 1000,
pollingTimer;

io.on('connection', function(socket){
  console.log('a user connected');
});

var updateSockets = function(data) {
    // adding the time of the last update
    t = new Date();
    t = moment().format('H:mm:ss');
    console.log('(%s) Connections: %s', t, connectionsArray.length);
    // sending new data to all the sockets connected
    connectionsArray.forEach(function(tmpSocket) {
    tmpSocket.volatile.emit('notification', data);
    });
};
console.log('server.js executed\n');

当我在 SSH OpenShift 上 运行 它只显示第一个 console.log 以及我的端口和 OpenShift 的 ipadress 以及我的 server.js 代码的最后一行:

server.js executed

就是这样。所以我没有像在本地测试时那样收到“用户连接”消息。

这是我想要在客户端 .js 文件中连接的方式:

var socket = io.connect('http://njs-uniqo.rhcloud.com:8080/');  

浏览器(Chrome)控制台输出:

> ?s=product&id=10:1 XMLHttpRequest cannot load http://xxx.rhcloud.com:8000/socket.io/?EIO=3&transport=polling&t=1430395459829-1.
> No 'Access-Control-Allow-Origin' header is present on the requested
> resource. Origin 'http://localhost' is therefore not allowed access.
> The response had HTTP status code 503.

如果我在客户端 .js 文件上将端口更改为 8080,我会得到 ERR_CONNECTION_TIMED_OUT:

GET http://xxx.rhcloud.com:8080/socket.io/?EIO=3&transport=polling&t=1430395346761-6 net::ERR_CONNECTION_TIMED_OUT

您需要使用端口 8000。这是 openshift 对 websocket 的强制要求。

 var socket = io.connect('http://yourapp.rhcloud.com:8000/',{'forceNew':true });

端口 8000 用于 http,8443 用于 https

Source

您必须编辑 package.json。添加...

"socket.io": "~0.9.16"

...在依赖项下。然后服务器会自动下载默认情况下不存在的 socket.io。