socket.io doesn't work on heroku - node.js

I'm new to socket.io and heroku.I wrote the simple chat system but when I publish that on Heroku it doesn't work.
app.js
var port = process.env.PORT || 3000;
var io = require('socket.io')(port);
// var url = require('url');
io.on('connection', function(socket,d) {
socket.on('sendMsg', function(data) {
console.log('SEND msg');
console.log(data);
io.emit('getMsg',data);
});
console.log(socket.handshake.query.id);
});
and in client :
<script src="http://chatserversm.herokuapp.com:3000/socket.io/socket.io.js"></script>
<script>
var socket = io('http://chatserversm.herokuapp.com:3000?id=2');
....
Where I was wrong ?

Your client attempts to connect to port 3000, but on Heroku process.env.PORT is set to 80.
Heroku only exposes port 80 (and 443 for SSL), so you will have to change your client to connect to that port.
Note that it should work just fine with an HTTP server on the same port.
Edit: here's what you should do.
First, you need your client to connect to the right port:
var socket = io('http://chatserversm.herokuapp.com:80?id=2');
Since port 80 is already implied, you can also write this as:
var socket = io('http://chatserversm.herokuapp.com?id=2');
Another similar issue is that you're trying to get socket.io.js from port 3000, so you also need to change to:
<script src="http://chatserversm.herokuapp.com/socket.io/socket.io.js"></script>

Related

How to run NodeJs SocketIO on server (Centos 7)

I create app with nodejs socket io. It works clearly at localhost (port: 3000). But when i deploy it to my server in there i can run my app on 3000 port but client side throw timeout. How can i solve it?
var fs = require('fs');
var https = require('https');
var options = {
key: fs.readFileSync('ssl.my-key.key'),
cert: fs.readFileSync('ssl.my-cert.crt')
};
var server = https.createServer(options);
var io = require('socket.io').listen(server);
var port = 3000;
const database = require('./Database');
io.on('connection', (socket) => {
socket.on('message', async (msg) => {
// I do some action here.
});
socket.on('disconnect', (msg) => {
// some action in here too
});
});
server.listen(port, () => {
console.log('listening on *:' + port);
});
It seems like your issue is with port forwarding.
In order for your server to be publicly accessed, it needs to have all ports forwarded appropriately. Locally and on the router.
Check this link to learn more about how to port forward on linux: https://linuxacademy.com/guide/11630-internal-port-forwarding-on-linux-using-the-firewall/
And this to learn more about router port forwarding, but this will really depend on your router.
https://www.noip.com/support/knowledgebase/general-port-forwarding-guide/
However, I don't recommend you to take care of hosting on your own machine(s). I
suggest you use Heroku, you can op in for their free servers, you don't need to pay.
More about heroku and NodeJS: https://linuxacademy.com/guide/11630-internal-port-forwarding-on-linux-using-the-firewall/
let we debug your node js app.
1) add some logs on database connection, http.createserver, also where you have to check if not success then catch exception
2) you should have to open port on centOs before start your node js app
3) you should have test you with domain name or ip address
as per you comment you got connection timeout , you mean node js server trying to connect with port 3000 but node not able to connect and its throws error with connection timeout
also send your sample code of your main index file so we can investigate your problen
thanks.

Socket.io port configuration with Heroku

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!
On the client side I ended up just declaring the socket like this:
const socket = io();
Leaving out the localhost:5000 part altogether.

WebSocket connection to 'ws://chattestarpit.herokuapp.com/' failed: Error during WebSocket handshake: Unexpected response code: 503

I am new to WebSocket (webRTC).I created a video chat app. it's working on localhost.
Server
app.listen(process.env.PORT || 8081, function () {
console.log("Example app listening at 8081" )
});
app.get('/', function(req, res){
res.sendfile('index.html');
});
//require our websocket library
var WebSocketServer = require('ws').Server;
//creating a websocket server at port 9090
var wss = new WebSocketServer({server: app});
//all connected to the server users
var users = {};
Client
//connecting to our signaling server
var HOST = location.origin.replace(/^http/, 'ws');
var conn = new WebSocket(HOST);
conn.onopen = function () {
console.log("Connected to the signaling server");
};
Heroku showing some problem with WebSocket. Thanks in advance.
Actually if you see "heroku logs", then you can find that the port on which app is running is a random 5 digit number. ( like 28896, 53365, etc.) It never actually runs on the second half || 8081.
You need to debug the actual root cause, what you can do is
Open terminal at your app folder
Type command heroku logs -t --app <your-app-name>
It will give all logs, including your nodejs based consoles
Based on that apply fixes accordingly
Hope that helps!
For me is was got the port from process.env.PORT and then it starts to work.
Heroku ignore completely my '.dev`s file

Connect to a heroku server with socket.io

How would one go about connecting to a heroku node.js server? For example, I have a server named 'https://example.herokuapp.com/' that uses node.js. How would I connect to it from a normal javascript file running socket.io. The code might look something like this:
var socket = io();
socket.connect('https://example.herokuapp.com/', { autoConnect: true});
I have tried this and I get the output of
polling-xhr.js:261 GET http://file/socket.io/?EIO=3&transport=polling&t=LjFlRl1 net::ERR_NAME_NOT_RESOLVED
So would I need an IP for the heroku server? If so how do I get it and is it even possible with heroku. If you're wondering why I don't host the html file on heroku it's because I'm using it for a website and my web host doesn't support node.js hosting. So I decided to host the node.js server on heroku. Thanks for your help in advance.
Server code:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
app.use(express.static(__dirname + '/public'));
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
io.on('connection', function(socket){
console.log('connection' + socket.id)
socket.emit('ping', {
data: 'ping',
});
});

NodeJS and socket.io app on Heroku with 2 ports

My app has an express server listening on one port (process.env.PORT) and I also want a web socket using another port. I used to use Express 3 with this set-up:
var express = require('express'),
http = require('http'),
io = require('socket.io'),
app = express();
server = http.Server(app);
ioServer = io(server);
ioServer.on('connection', callback);
server.listen(process.env.PORT || 3000, function () {
console.log('App listening on ' + server.address().port);
});
The above code worked fine, as when creating ioServer, no specific port is required. However, after I switched to Express 4 and started using Heroku's WebSocket service, I had to specify a port like this:
var WebSocketServer = require('ws').Server,
port = 5000,
server = http.createServer(app);
server.listen(port);
var wss = new WebSocketServer({server: server});
wss.on('connection', callback);
app.listen(app.get('port'), function() {
console.log('Express server listening.'));
});
This new set-up never works because when I run the app on Heroku, I get an error complaining that the same port can't be used twice:
Error: listen EADDRINUSE :::40854
The set-up logic is essentially the same except for explicitly assigning a port in Express 4, so why did my code work with Express 3 but not Express 4? How should I fix this?
In your second code block, you can't call .listen() on both your server and on your app object. In this particular case (the way you've structured your code), you only want to call it on the server object, not on app.
This is the code from Heroku's dev page on this topic:
var WebSocketServer = require("ws").Server
var http = require("http")
var express = require("express")
var app = express()
var port = process.env.PORT || 5000
app.use(express.static(__dirname + "/"))
var server = http.createServer(app)
server.listen(port)
console.log("http server listening on %d", port)
var wss = new WebSocketServer({server: server})
console.log("websocket server created")
Also, your first code block is not running on two ports. As is usually the design for webSockets, a single port is used for both your web requests and your webSocket connections. The web server itself splits out the two types of connections based on the initial connection.

Resources