Socket.io is not connecting on Heroku - node.js

I am using Socket.io in my NodeJS backend. However, the sockets do not work. For example, one should receive a link and then send them to all other rooms under the same code, but the code is not executing. In my heroku logs I receive no errors but when I inspect element the page I get
polling-xhr.js:268 GET https://localhost:5000/socket.io/?EIO=3&transport=polling&t=NDADDNH net::ERR_CONNECTION_REFUSED
and
Failed to load resource: net::ERR_CONNECTION_REFUSED
I have looked into similar problems from this forum and made several changes but none of them have solved the issue. Also a bunch of the posts answer with solutions for ws in general which I don't understand at all :/
From what I read the issue might be with my ports? I followed a few of them but the same errors still occured.
Socket.io:
/***BACKEND***/
const express = require('express');
const path = require('path');
const app = express();
let rooms = [];
/***SERVER***/
const port = process.env.PORT || 5000;
server = app.listen(port, function(){
console.log('App is listening on port ' + port)
});
/***SOCKET.IO***/
const socket = require('socket.io');
io = socket(server);
io.on('connection', (socket) => {
//bunch of functionality
}
and then in my client I am using
this.socket = io('localhost:5000');
//one of the functions
this.syncQueue = () => {
this.socket.emit('SYNC_QUEUE', {
activeRoom: this.props.getRoom()
});
}
this.socket.on('RECEIVE_QUEUE', newQueue => {
props.onAddToQueue(newQueue);
});
FYI Everything works on localhost

Localhost will not work on the server and if you are using default namespace you no need to specify the URL. So try this, this.socket = io()

On the client side, you're trying to connect to localhost:5000 instead of the URL Heroku provides. Try this this.socket = io('heroku url goes here').

Related

socketio, client can connect to server if hosted locally, but returns error when trying to connect to server hosted on seperate vserver

I am trying to make a simple server with socket.io and express and connect to it through a website.
when i followed a tutorial on socketio with localhost, everything worked fine, but when i put the server on a vserver, and tried to connect to it, i got this error:
Failed to load resource: net::ERR_SSL_PROTOCOL_ERROR
as well as:
GET https://54.53.0.254:47185/socket.io/?EIO=4&transport=polling&t=O09jjrs net::ERR_SSL_PROTOCOL_ERROR
here is my server code:
const express = require('express');
const app = express();
const server = app.listen(47185);
const socket = require('socket.io');
const io = socket(server)
console.log('server running on port 47185');
io.sockets.on('connection', newConnection);
function newConnection(socket) {
console.log('new connection: ' + socket.id);
socket.on('input', inputLog)
function inputLog(data) {
socket.broadcast.emit('input', data);
console.log(data);
}
}
and here is my client code (this is all that relates to socket.io, the rest is just for the website)
var options = {
rejectUnauthorized:false
}
var socket;
socket = io.connect('89.58.0.199:47185', options);
socket.on('input', foreignInput)
function foreignInput(data) {
terminal_animate('\n' + data)
}
i have tried many different fixes and googled everything i can think of, and i'm just not sure what the problem is.
can anyone help me out with this issue? thanks in advance.
In the documentation, according to the Client Initialization part, in node.js you should provide the protocol when connecting to the server.
// the following forms are similar
const socket = io("https://server-domain.com");
const socket = io("wss://server-domain.com");
const socket = io("server-domain.com"); // only in the browser when the page is served over https (will not work in Node.js)
The first two example shows the secure https/wss as protocol, for that you need to serve the required files from the server, example in the documentation.
With http/ws as protocol it should work, but the communication will not be secure.
The Server Initialization / With Express shows an example to call .listen on the return value of createServer from the http module, with the app given as a parameter.
const express = require("express");
const { createServer } = require("http");
const { Server } = require("socket.io");
const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, { /* options */ });
io.on("connection", (socket) => {
// ...
});
httpServer.listen(3000);
With a caution that says:
Using app.listen(3000) will not work here, as it creates a new HTTP server.

Using sockets with express in production environment(heroku)

While working with localhost I used the following code to implement socket functionality-
Server Side
var express = require('express');
var app = express();
const io = require('socket.io')(5000);
Client Side
<script src="http://localhost:5000/socket.io/socket.io.js"></script>
<script>const socket = io.connect('http://localhost:5000');</script>
The above code worked fine for me locally. Earlier tried use the code given in the official documentation, but it did not work. I got a 404 error when trying to load socket.io.js file and it said 'io is not defined' on the client side. That code is given below-
Server Side
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
Client Side
<script src="/socket.io/socket.io.js"></script>
<script>var socket = io.connect('http://localhost');</script>
Now I need to deploy the app to Heroku and don't know how to do the socket functionality. I tried both the above ways but none worked in Heroku. I am getting '404 error' and 'io is not defined'. The server-side code is written in ./app.js and client-side code written in ./public/index.html.
How do I get this socket functionality to work in Heroku and also why is the official code not even working locally?
Trying to get the same thing working, don't have all the answers but on heroku you need to grab the port from the environment variable.
// Needed for Heroku serving
if (process.env.PORT > 0)
port = process.env.PORT;
else
port = 5000;
// create the express server (app) and the socket io server (io)
const app = express();
const server = app.listen(port, () => {
console.log("Listening on port: " + port);
});
const io = require('socket.io')(server);
Client Side
const socket = socketIOClient('APPNAME.herokuapp.com:80');
socket.emit("MsgType", "Payload")

Heroku socket.io server runs locally, but not anywhere else

Basically my socket.io server is only working for.. one computer only, I suppose. It works if I use Chrome, Chrome incognito, Edge. I tried using the app with my phone, while on the same Wifi, and that's where I encountered problems. It looked like socket.io just wouldn't work then. I feel like it's only working for one client (maybe ip, port issues?)
I use socket.io in pair with React js, and oh boy it was pain in the arse to make them work both locally and on Heroku.
Here's my server file /src/server/index.js
const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const axios = require("axios");
const port = process.env.PORT || 4001; // Only this port works for some reason
const index = require("./routes/index");
const app = express();
const path = require('path');
const server = http.createServer(app);
const io = socketIo(server); // < Interesting!
io = socketIo.listen(app);
io.configure(function () {
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10); // Recommended from online guys
});
app.use(express.static(path.join(__dirname, '../../index')));
app.get('/', (req, res, next) =>
res.sendFile(index))
io.on("connection", socket => {
console.log("New client connected");
})
server.listen(port, () => console.log(`Listening on port ${port}`));
I use config file to dynamically change the server and I import it every time I need to connect to my socket via socket.io-client
let server = 'ws://XXXXXXXXXXXXX.herokuapp.com/socket.io/?EIO=4&transport=websocket';
const env = process.env.NODE_ENV;
if (env === 'development') {
server = 'http://127.0.0.1:4001';
}
module.exports = server;
What could be the problem? Why is only working on my root computer? Could be a dyno problem or something else?
I'm a complete beginner with both heroku and socket.io, so any information would be helpful.
**EDIT:
I am not sure, but I feel like a server running in my VS Code made it work in my heroku app. I have turned it off and the server just keeps sending net::ERR_CONNECTION_REFUSED error.
Solution:
Using mars/heroku-cra-node buildpack is a must. It seperates react-ui and server code. Port config: const port = process.env.PORT || 4001,
Client listens for: let server = window.location.hostname
Also good to have a seperate config file for clientside that has the following:
const env = process.env.NODE_ENV;
if (env === 'development') {
server = 'http://localhost:4001';
}
module.exports = server;
Then you won't have to change ports and servers in development (VSCode) or production (Heroku).

Error: http://localhost:3001/socket.io/ 404 (Not Found)

I am trying to connect client-server using socket.io however at the moment of testing my code I am getting this error http://localhost:3001/socket.io/?EIO=3&transport=polling&t=MgUqscg 404 (Not Found)
I already tried two different ways to achieve this. One returns the error already specified the second one returns an error listen EADDRINUSE :::3001
can somebody please explain to me what am I doing wrong? all tutorials seem so easy but I am stuck at this point and I really want to learn how to use sockets to improve my skills.
This is my code for server
const express = require('express');
const http = require('http');
const app = express();
// Web socket config option #1
var server = http.Server(app);
var io = require('socket.io')(server);
// Web socket config option #2
var io = require('socket.io').listen(server);
server.listen(PORT)
const PORT = process.env.PORT || 3001;
app.set('port', 3000)
io.on('connection', (socket) =>{
console.log('a user is connected')
})
app.listen(PORT, function(){
console.log(' ======= SERVER RUNNING =======');
})
This is my code for client
import * as io from 'socket.io-client';
private socket = io(`http://localhost:3001`)
I just want to connect client-server successfully without errors and print to console a success message. Thanks in advance.
two thing from my experience.
remove app.listen official doc
upgrade problem official doc
cheers,
hope it can help you
I solved it by using a different port for sending secket.io events.
server.listen(4444)

What am I doing wrong in socket.io configuration?

I'm trying to add instant messaging to an existing app. But I'm not sure how should configure socket.io module.
I've already tried the following:
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
const config = require('./config/config.js');
var expressConfig = require('./config/express.js').front,
models = require('./app/models'),
passConfig = require('./config/passport-front.js');
const app = expressConfig();
const passport = passConfig();
app.set('port', config.frontPort);
const http = require('http').Server(app);
const io = require('socket.io')(http);
io.on('connection', function (socket) {
console.log('Connected');
});
models.sequelize.sync().then(function () {
var server = http.listen(app.get('port'), function () {
console.log('Express server listening on port ' + server.address().port);
});
});
module.exports = http;
Since connected is not being logged when I open a page I'm assuming something is missing. Where is my mistake?
You didn't show your client-side code so it's hard to tell you what's wrong. Do you get any error in the browser? What is the network traffic on the browser? Without that it's hard to tell anything specific.
Take a look at this answer:
Getting data from/writing data to localhost with Express and Socket.io
It has a working example of something similar to what you're trying to do.
In general - remember that you need to include the socket.io client-side code in the browser:
<script src="/socket.io/socket.io.js"></script>
and then you need to connect with io() with something like:
var s = io();
s.on('color', function (color) {
document.body.style.backgroundColor = color;
});
The 'color' here is just an example that comes from this project on GitHub:
https://github.com/rsp/node-live-color
It's an example of a website that changes colors selected in messages that come vie socket.io.

Resources