简体   繁体   中英

SocketIO is not working in Heroku Environment [Works in Localhost]

I developed chat program with NodeJS and SocketIO. Then I deployed to Heroku Server and I found that SocketIO is not working in Heroku.

I already checked the log in Heroku but there are nothing. But it is weird that it is working in localhost but not in Heroku environment. I think there are some problem with PORT Setting.

[Server Side Code]

/* Socket IO Settings */
const server = require('http').Server(express);
const io = require('socket.io')(server);
let port = process.env.PORT || 3001;
server.listen(port, function () {
  console.log(`SocketIO Listening on port : ${port}`)
});

[Client Side Code]

/* Chat Functions */
var socket = io.connect(`${window.location.hostname}:3001`);

At first time I just use var socket = io.connect('http://localhost:3001'); code and it works well in Localhost Env. But after I deployed to heroku I add Heroku Variable to use it in production.

[PORT Setting]

NODEJS Server : 3000
SOCKET IO : 3001
Heroku process.env.PORT : 3001 (But When I check Heroku console it changes everytime when I reload the dynos and in Logs said me that the ports are already in use.)

I already read Heroku Document but it seems that I create NodeJS App with Express Generator I think it should be different solution. I already tried heroku document but it's not working

Set your server ip in server.listen function

var ip='127.0.0.1';
var port ='3001' ;
server.listen(ip,port, function() {console.log('server stsrt in ip: ' +ip+' and port: ' +port);}) ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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