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

て烟熏妆下的殇ゞ 提交于 2019-12-22 12:43:04

问题


I can't get socket.io running on OpenShift. I googled for some hours now but nothing really helped me. Locally it works fine (with different ports and localhost as host of course).

This is my server.js file:

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');

When I run this on SSH OpenShift it just shows the first console.log with my port and ipadress of OpenShift and the last line of my server.js code:

server.js executed

and that's it. So I don't get the "a user connected" message like when I test it locally.

This is how I want to connect in my client-side .js-file:

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

Browser (Chrome) Console outputs:

> ?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.

If I change the port to 8080 on the client-side .js-file I get ERR_CONNECTION_TIMED_OUT:

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

回答1:


You need to use port 8000. It's what openshift forces for websockets.

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

Port 8000 is for http and 8443 is for https

Source




回答2:


You must edit package.json. Add...

"socket.io": "~0.9.16"

...under dependencies. The server then automatically downloads socket.io which is not present by default.



来源:https://stackoverflow.com/questions/29967914/cant-get-socket-io-and-nodejs-running-with-openshift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!