Socket.io.js returns 404 on OpenShift - node.js

I'm new to node.js and I'm trying to create a chat app following the tutorial on socket.io's website. I've got it working on my local machine, but now I'm trying to upload it to an OpenShift Server.
In my app, I have the line:
<script src="/socket.io/socket.io.js"></script>
On my local machine, it loads fine, but on my server, it returns a 404 error. I thought that my node_modules might not be loading at first, but after shh-ing into the server and checking, I see they are present.
My dependencies in my package.json are as follows:
"dependencies": {
"express": "^3.4.8",
"socket.io": "^1.1.0"
}
There are many different questions on here about getting a 404 error from socket.io and I've gone threw many of them them attempting to solve this issue, with no progress. Including changing the script src to:
http://app-domain.rhccloud.com
http://app-domain.rhccloud.com:8000
http://app-domain.rhccloud.com:8080
ws://app-domain.rhchloud.com:
Most of the suggestions aren't specific to an OpenShift server so I figured I'd ask specifically about it.
If needed, here's my server.js:
#!/bin/env node
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var ip = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
app.get('/', function(req, res){
res.sendfile('index.html');
});
app.listen(port,ip,function() {
console.log('listening');
});
io.on('connection',function(socket) {
console.log('a user connected');
socket.on('disconnect',function() {
console.log('user disconnected');
});
socket.on('chat message',function(msg) {
io.emit('chat message',msg);
});
});
Thanks for any assistance.

Should be:
server.listen(port,ip,function() {
console.log('listening');
});
not app.listen.

Related

Error occurred while trying to proxy request [...] from 192.168.0.4:3000 to http://192.168.0.4:5000 (ECONNRESET)

I'm working on my first project using react and node and have been stuck on this problem for a while. I keep getting this error when trying to connect to my site using the ip address, but if I just do localhost:3000 it works perfectly. I want to be able to connect via the IP address so I can test it across devices. Here is the full error:
[HPM] Error occurred while trying to proxy request /socket.io/?EIO=3&transport=polling&t=N4EqtUl&sid=kz_I098ZM2h1Z6WZAAAI from 192.168.0.4:3000 to http://192.168.0.4:5000 (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors)
I checkout out this post and implemented setupProxy.js like the second answer suggested, but it still isn't working.
Here is my node server (index.js):
const express = require('express');
const app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
const path = require('path')
const port = process.env.PORT || 5000;
app.use(express.static(path.join(__dirname, 'client/build')));
io.on('connection', function(socket) {
console.log('a user connected');
});
// Anything that doesn't match the above, send back index.html
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/client/build/index.html'))
})
http.listen(port || 5000, function () {
console.log('listening on', port);
});

Socket.io works with localhost but not on Heroku server

I am currently trying to use socket.io and a node.js server to communicate with a Unity script. I have everything hooked up and working with localhost, but for some reason when I port it to my Heroku server it can't connect. I'm assuming it might have something to do with the URL's? I'm new to socket.io so any help would be appreciated.
My node.js server:
var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);
var path = require('path');
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(socket) {
socket.on('beep', function(){
socket.emit("speed", {data: 5});
console.log('beep recieved');
});
socket.on('change-speed', function(data) {
console.log('change speed recieved: ' + data);
socket.emit("speed", {newSpeed: data});
});
socket.on('ios-connection', function(data) {
console.log('ios connection with message: ' + data);
});
});
app.set('port', (process.env.PORT || 5000));
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
My connection URL:
ws://<heroku app name>.herokuapp.com:5000/socket.io/?EIO=4&transport=websocket
The problem is almost certainly an incorrect port number.
In your application, you are checking for process.env.PORT and if it is not set, you are defaulting to 5000.
In your ws URL however, you seem to be always expecting your application to be listening on port 5000.
You can check the config settings of your application by running the following command in the root of your project:
heroku run printenv
This will print a list of config vars, including the current set PORT value, eg:
PORT=9352
You should use this port when constructing your ws URLs, eg:
ws://your-app.herokuapp.com:9352/socket.io/?EIO=4&transport=websocket
I found the way!!.
In Unity
if you run server in the localhost. the url should have " : port"
example (port = 5000)
ws://127.0.0.1:5000/socket.io/?EIO=4&transport=websocket
but if you have deployed to **heroku
the url must delete " : port"
ws://<heroku app name>.herokuapp.com/socket.io/?EIO=4&transport=websocket
It's work for me!
I have deployed your code with minor changes and its working fine on heroku please take a look into it.
Server side app.js
var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 5000));
var server = app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
var io = require('socket.io')(server);
app.use(express.static("./views"));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.get('/', function (req, res) {
var path = __dirname + '/views/index.html';
console.log(path);
res.sendFile(path);
});
io.on('connection', function(socket) {
socket.on('beep', function(){
socket.emit("beep", {data: 5});
console.log('beep recieved');
});
socket.on('change-speed', function(data) {
console.log('change speed recieved: ' + data);
socket.emit("speed", {newSpeed: data});
});
socket.on('ios-connection', function(data) {
console.log('ios connection with message: ' + data);
});
});
package.json
{
"name": "socketio",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start" : "node app.js"
},
"author": "inampaki",
"license": "ISC",
"dependencies": {
"express": "^4.13.3",
"express-ws": "^0.2.6",
"socket.io": "^1.3.7"
}
}
index.html
<script src="/socket.io.js"></script>
<script>
var socket = io.connect('/');
socket.on('speed', function (data) {
console.log('speed Message Received!');
console.log(data);
});
socket.on('beep', function (data) {
console.log('beep Message Received!');
console.log(data);
});
socket.emit("beep", {beep : true});
socket.emit("change-speed", {"change-speed" : true});
socket.emit("ios-connection", {"ios-connection" : true});
</script>
note that save index.html and socket.io.js in views folder. URL on which I have deployed it is socketip
Ok, for some reason I tried everything on this question thread, and it worked. However not a single answer worked, but a combination of every one.
First, I removed the :PORT part in the URL, sort of like Chinnawat Sirima says. It is now...
ws://.herokuapp.com/socket.io/?EIO=4&transport=websocket
Then, for some reason initiating the server with this code from dangalg's answer/teyou's repo did work (I also noticed teyou's url doesn't have the port either).
var express = require('express');
var app = express();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var PORT = process.env.PORT || 3000;
(more code here)
http.listen(PORT,function(){
console.log("Listening to port " + PORT);
});
Why do I say "for some reason"? Because I still don't know what I did lol. My guess is that I was setting the server in a way Heroku didn't like, but everyday localhost does. Because localhost doesn't care.
I'm just recompiling this because I've been in frustration with this problem for the last 8 hours, more or less. So I hope this helps someone else, to not lose valuable time and sleep.
(btw, I don't have a PORT variable in my Heroku, I have some other name, I guess that's another useless line but I'm not touching this anymore in case I break it again :D).
If you have deployed your application to Heroku, remove the port number from the URL of the server as given and it should work fine.
ws://<heroku app name>.herokuapp.com/socket.io/?EIO=4&transport=websocket When you test the app locally, you can access the socket via http://localhost:YOUR_PORT_NUMBER wheres, after deployment, you don't need to specify the port.
Had a bit of a nightmare with this. Ended up reading through the docs.
Server: https://www.npmjs.com/package/socket.io
Client: https://socket.io/docs/v4/client-initialization
It seems my structure was wrong see the docs.
In conjunction with Express
const app = require('express')();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.on('connection', () => { /* … */ });
server.listen(3000);
My full code.
const express = require('express')
const path = require('path');
const http = require('http')
const PORT = process.env.PORT || 5000
const app = express()
const server = http.createServer(app)
const cors = require("cors");
app.use(cors());
// Serve static files from the React app
app.use(express.static(path.join(__dirname, 'client/build')));
const io = require('socket.io')(server);
io.on("connection", (socket) => {
});
server.listen(PORT, () => console.log(`Server is running on port ${PORT}`));
And in my react code I am simply using.
const socket = io();
Hope this helps someone else

Node.js + Socket.io on heroku fail to get socket.io/socket.io.js

First i'd like to thank you for taking the time to try to help me.
I'm trying to do a web application online using node.js and socket.io for realtime.
Here is my problem when i try my application in local it works but when i pushed it on heroku the server can't find my
"herokuApp.heroku.com/socket.io/socket.io.js"
Of course i searched a lot for solve my problem but nothing here has solved it.
Here is my files :
var express = require('express');
var app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
ent = require('ent'), // Disable HTML caracters (equal htmlentities in PHP)
fs = require('fs');
app.use(express.static(__dirname + '/public_html'));
app.set('port', (process.env.PORT || 5000));
server.listen(5000);
io.sockets.on('connection', function (socket) {
socket.on("newMsg", function(data){
console.log("the client message: " + msg);});
});
app.get('/', function(request, response) {
response.send('Hello World!');
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
and in my index.html
<script src="/socket.io/socket.io.js"></script>
I add some information like the server response when i push my commit :
http://puu.sh/irF05/e1c648c627.png
and the structure of my files :
http://puu.sh/irF8V/8240318ae6.png (the code above is from index.js and i don't use server.js)
Thanks you again for having read this, i'm not really familiar with node or socket so please excuse me if the solution is simple.
Make sure that socket.io.js is actually being pushed to the Heroku repository. Do a git status and make sure that it isn't untracked by git. Additionally, it might help if you post what your folder structure for this project looks like (at least the relevant files)

Application Error when attempting to deploy Node.js/Express/Socket.io application on Heroku

I am fairly new to all of these technologies (including somewhat JavaScript) so you might have to bear with me here.
I followed the ChatApp tutorial over at Socket.IO docs fairly closely and modified the application to my likings somewhat; however, I don't think I changed much on the side of server interaction and stuff. My problem is no matter what I do, I can't seem to be able to get my application to successfully run on Heroku. I get this error message when trying to load the app:
Application Error
An error occurred in the application and your page could not be served. Please try again in a few moments. If you are the application owner, check your logs for details.
I am not sure if I am missing something obvious or what.
Here is my main index.js file:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('index.html');
});
app.use("/css", express.static(__dirname + '/css'));
//array of users currently in chat
var people = {};
io.on('connection', function(socket){
console.log('user connected!');
socket.on('join', function(name){
people[socket.id] = name; //create entry in 'people' with new user
socket.emit("update", "You have connected to the server.");
io.sockets.emit("update", name + " has joined the server.");
io.sockets.emit("update_people_list", people);
});
socket.on('disconnect', function(){
console.log('user disconnected!');
if(people[socket.id] != ""){
io.sockets.emit("update", people[socket.id] + " has left the server.");
delete people[socket.id];
io.sockets.emit("update_people_list", people);
}
});
socket.on('chat message', function(msg){
console.log('message: ' + msg);
io.sockets.emit('chat message', people[socket.id], msg);
});
});
// http.listen(3000, function(){
// console.log('listening on *:3000');
// });
index.html
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery.js"></script>
<script>
$(document).ready(function(){
var ready = false;
var socket = io.connect();
$("#chat").hide();
$(".canvasDiv").hide();
$("#name").focus();
//prevent form from being submitted without name
$("form").submit(function(event){
event.preventDefault();
});
//allows entering by hitting 'Enter' for name
$("#name").keypress(function(e){
if(e.which == 13) { //if ENTER key
var name = $("#name").val();
if(name != ""){
socket.emit("join", name);
$("#login").detach();
$("#chat").show();
$("#msg").focus();
ready = true;
}
}
});
$('#chatform').submit(function(){ //when submit chat message
socket.emit('chat message', $('#msg').val()); //emit message + value of input
$('#msg').val(''); //empty field?
return false; //so that the page doesn't refresh
});
//SOCKET LISTENING
socket.on('chat message', function(user, msg){
if(ready){
$('#messages').append("<p><strong><span class='chat-user'>" + htmlEntities(user) + " </span></strong>: " + htmlEntities(msg) + "</p>");
//adjust height and scroll as need be:
var $container = $('#messages');
var height = $container.get(0).scrollHeight;
$container.scrollTop(height);
}
});
socket.on("update", function(io_message){
if(ready){
$('#messages').append("<p class='notification'>" + htmlEntities(io_message) + "</p>")
}
});
socket.on("update_people_list", function(people){
if(ready){
$("#people").empty(); //clear to refresh it
$.each(people, function(client_id, name){
$('#people').append("<p class='notification'>" + htmlEntities(name) + "</p>");
});
var $container = $("#messages");
var height = $container.get(0).scrollHeight;
$container.scrollTop(height);
}
});
});
</script>
Additionally, my package.json file
{
"name": "socket-chat-example",
"version": "0.0.1",
"description": "my first socket.io app",
"dependencies": {
"express": "^4.6.1",
"socket.io": "^1.0.6"
}
}
Procfile:
web: node index.js
.gitignore:
node_modules/
Disclosure: I'm the Node Platform Owner at Heroku
First, you should run heroku logs to get logging output.
Second, do you mean to have commented out listen on your server? Without this, your server won't allow any incoming connections:
// http.listen(3000, function(){
// console.log('listening on *:3000');
// });
Finally, instead of binding to a hardcoded port (3000), you should bind to an environment variable with a default:
http.listen(process.env.PORT || 3000, function(){
console.log('listening on', http.address().port);
});
I encountered the same error, but including "start":"node app.js" in package.json file tends to fix the problem. Hope this helps anyone that encounters the same error.
Note: app.js should be your own main server file.
After checking heroku logs I was able to find out that my bcrypt dependency defined properly in package.json. I would recommend you:
Check that your dependencies have the right versions attached to them.
Delete node_modules file
Run npm install
Check if all the dependencies installed properly
If they have installed properly, then git push heroku
I also encountered this error after not using my Node app for several weeks. The reason appeared to be that not only had the app gone to sleep, but the database and its connection had too. I'm using a free MongoDB instance hosted by MongoLab.
I fixed this by running my local copy of the app, causing MongoLab to awaken. Then after a few minutes, my Heroku-hosted app started working again.
Check all your dependency.
You could confirm it by cross checking your package.json or rather do refresh installation of all the dependencies in your package.json

Can't get socket.io.js

I'm actually working on a little project, where i'm supposed to recreate a drawing multiplayer game with node.js, mongoDB, socket.io and canvas.
The drawer is working like a charm, and the server seems to work well too. I got my register/login/sessions and database up and working, the only problem is socket.io. When an user is joining the game room, he can see the drawer and tools, but no connection. Why ? The browser can't find socket.io.js.
What I did :
I verified if it was installed, it is with npm install socket.io.
I checked if the server was starting it when turning the server on : Got "socket.io started" in my console.
I checked my HTML code, here it is :
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
According to the billions of tutorials/dev sites/help subjects, this is supposed to work. But it's not. When opening the console of my browser, I got this :
X GET http://localhost:1337/socket.io/socket.io.js NOT FOUND.
I don't know where is the problem, I can't figure this out and it's giving me a huge headache.. So I'm here.
Thanks in advance for helping ! :)
Given the code in your comment, you're not using the correct variable for initializing socket.io.
Try this:
var express = require('express');
var app = express();
var server = app.listen(1337);
var io = require('socket.io').listen(server);
...
So instead of having socket.io 'listen' on the Express app instance, it should listen to what app.listen(...) returns (which happens to be an http.Server instance).
For anyone landing here because they're going through the v4.x socket.io get started example, all you need to do is add another endpoint to your index.js file
index.js
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
// add this
app.get('/socket.io/socket.io.js', (req, res) => {
res.sendFile(__dirname + '/node_modules/socket.io/client-dist/socket.io.js');
});
///
io.on('connection', (socket) => {
console.log('a user connected');
});
server.listen(3000, () => {
console.log('listening on *:3000');
});

Resources