Ad

Socket.io Port Configuration With Heroku

- 1 answer

I'm trying to get socket.io working on my heorku app, but I think I'm having some trouble defining the ports. On the backend I have my express app listening to the process.env port or 5000, and I have my socket.io port listening on 8000.

Node.js

const express = require("express");
const app = express();
const server = require('http').Server(app)
const io = require('socket.io')(server)

const socketPort = 8000;
io.listen(socketPort);

const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port} !`));

And on my front end I have my socket to route requests to localhost:8000

Reactjs

const socket = io('http://localhost:8000')

//Open connection to backend
socket.on('connect', ()=>{
    console.log("Connected");           
})

It works just fine when I run it locally, but I can't get it working on Heroku - GET http://localhost:8000/socket.io/?EIO=3&transport=polling&t=MszLUDm net::ERR_CONNECTION_REFUSED

Is there a specific way I need to set up these ports? As far as I know I can only set up one process.env port. Should I be subbing something into the "localhost:8000" on the front end?

Thanks!

Ad

Answer

On the client side I ended up just declaring the socket like this:

const socket = io();

Leaving out the localhost:5000 part altogether.

Ad
source: stackoverflow.com
Ad