'Heroku and Socket.io not listening on the same port
So I am coding this web on Heroku and I try to integrate a socket into the setup. But the problem is that I cannot make both my Heroku app and socket.io server listen to the same port.
The default port for Heroku seems to be 5000 and for socket.io seems to be 3000.
If I try to change either of the ports to the same as the other, then the EADDRINUSE error pops up.
However, if I don't, then the two processes seems to operate separately
when I run npm start, then the terminal says
Listening on 5000
listening on xoxo 3000
And when I turned on to localhost:3000 it actually works ( the socket.io ), but on localhost:5000 it obviously doesn't. As a matter of fact, it also doesn't work on the Website that Heroku generated for me (only the localhost:5000 showed up)
The code lines below are from my index.js file.
How could I fix this? Thank you in advance.
const express = require('express');
const app = express();
const path = require('path')
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
const PORT = process.env.PORT || 5000;
const INDEX = '/index.ejs'
app.listen(PORT, () => console.log(`Listening on ${ PORT }`))
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.get('/', (req, res) => res.render('index'));
io.on('connection', (socket) => {
socket.on('playerEvent', (msg) => {
console.log(msg);
});
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
socket.broadcast.emit('hi');
});
server.listen(3000, () => {
console.log('listening on xoxo 3000');
});
//socket.on('playerEvent', function(msg){
// console.log(msg);
//});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
