Socket.io, server not responding to connection event - node.js

I have a managed server at cloudways. I am trying to use socket.io.
client.php:
var socket = io('http://localhost:3000');
console.log(socket);
server.js:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000);
io.on('connection', function(socket){
console.log('is connected');
});
When visiting the page, I see two instances of 200 OK in the network section of the console.
The console in the browser also prints the socket variable, which has "connected : true".
However, I DO NOT see "is connected" in the terminal (from server.js), it is just blank.
This site has worked locally, but these problems are appearing when trying to get it to work at Cloudways.
Any ideas?
I have tried switching "localhost" to both the domain name and the IP-address, and I have tried different ports, but 3000 is the only one that will let me start the server.js without error.
EDIT
Cloudways have confirmed that port 3000 should be used.
I have tried changing the url in io() to:
var socket = io('http://my-cloudways-url:3000'); (net::ERR_EMPTY_RESPONSE)
var socket = io('http://www.my-domain.club:3000'); (net::ERR_EMPTY_RESPONSE)
var socket = io('http://ip-adr:3000'); (net::ERR_EMPTY_RESPONSE)
And today I am getting
var socket = io('http://localhost:3000'); (net::ERR_CONNECTION_REFUSED)
I have also tried io.connect(using the same adresses / ports).

Maybe is your php index... Because you are setting the localhost and the port.
I'm not sure about how Cloudway works. But, when we run the server.js, some clouds give some url for access our projects...
In your cloudways try to use the official URL that they given to you access the project:
var socket = io.connect('url.from.cloudway');
For example, I'm using cloud9, and when I execute the server.js, return one url like:
Your code is running: https://demo-some-id.c9.io
And when I'm using socket.io, I need to set in my index the URL parameter inside the IO.
var socket = io('https://demo-some-id.c9.io');
You need to add the client-side socket.io.js version and add the script tag with the path, like:
<script src="js/socket.io.js"></script>
Obs.: Some clouds, you need to set the url in your <script> tag
<script src="https://demo-some-id.c9.io/socket.io/socket.io.js"></script>

Related

Server responds with 404 when trying to connect Socket.io to an Express app

I'm building a VueJS app using vue-cli's webpack template.
I've split the front and back ends into different Heroku applications and deployed them.
Background:
My client app has the same setup as described here
tl;dr the above Medium article:
We now have a fresh Vue-cli/webpack app, and a server.js file used to create an Express server that serves the built app files.
The problem:
I've been running into issues trying to use socket.io on said server.js file.
Here's how server.js looks like:
var http = require('http'),
path = require('path'),
express = require('express'),
app = express(),
server = http.createServer(app),
socketIO = require('socket.io'),
port = process.env.PORT || 8080,
history = require('connect-history-api-fallback'),
serveStatic = require('serve-static')
app.use(serveStatic(path.join(__dirname, '/dist')))
server.listen(port, () => {
// logs when running node server.js
console.log('listening on port', port)
})
const io = socketIO(server);
io.on('connection', (socket) => {
console.log('Connected!!!');
});
And this is how I call socket.io inside of my .vue component:
const io = require('socket.io-client')
const socket = io('http://localhost:8080')
As soon as this last line is uncommented I receive a friendly Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:8080/socket.io/?EIO=3&transport=polling&t=M9yJX8nsocket.io/?EIO=3&transport=polling&t=M9yHe0F
Additional info:
Not sure if relevant, but still saying - I'm Using "connect-history-api-fallback" to point all non-existent routes to a wildcard 404 .vue component that displays a friendly user message and allows them to go back to existing routes.
Can this be a part of the reason? What I read about my issue is that I probably have trouble making socket.io run on the same server that my app is running in.
I experienced the problem initially when trying to first connect my Vue App with Vue-Socket.io
upon the line
Vue.use(VueSocketio, socketio('http://socketserver.com:1923'));
Where as an URL I used http://localhost:8080
I've spend a good few days on the problem and still have no clarity on where this problem is rooted in. I am really trying to understand and would highly appreciate any form of feedback. I read about people having the same / similar problem, and tried calling io() without my localhost + port url.
First question here, hope it's properly asked.
Okay, guys, I don't know why, but following the code placed in the "Docs" section of Socket IO's website resulted in the same error (Express 3/4 section). I then went on to copy the Chat demo and had success, so I'm now importing Socket.IO in my Index.html file
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
With server.js looking like this:
var path = require('path'),
app = require('express')(),
http = require('http').Server(app),
io = require('socket.io')(http),
port = process.env.PORT || 8080,
history = require('connect-history-api-fallback'),
serveStatic = require('serve-static')
app.use(serveStatic(path.join(__dirname, '/dist')))
http.listen(port, () => {
console.log('listening on port', port)
})
io.on('connection', (socket) => {
console.log('Connected!!!');
});
I'm going to close this now and see how to implement the functionality I'm looking for - I now have a good starting point. Best of luck to anyone struggling with this.
Cheers!

How to make Socket IO work over HTTPS using node.js

This is frustrating me like crazy!
i'm using a proxy so that any requests that go to myurl/APP/ are answered by node.js at myurl:8001
I now need this to work over https. easy.... i thought.
i have Apache serving up the old version from the public folder. That is stand alone, and when i'm done building this, it will just be removed. but for now needs to remain in tact and accessible. Lets encrypt is setup on this. and https://myurl works fine, showing content from the public folder of course.
if i go to https://myurl:8001 then chrome says "site can't be reached". If i go to http://myurl:8001 it works fine. I think this is because https default port is 443. I have VPS not dedicated so i don't think i can alter that. And surely if i did alter the ssl port then it wont work for the public folder??
i'll show you the basics of whats going on;
app.js;
var express = require('express');
var app = express();
var serv = require('http').Server(app);
app.get('/',function(req, res) {
res.sendFile(__dirname + '/client/index.html');
});
app.use('/client',express.static(__dirname + '/client'));
serv.listen(8001);
console.log("Server started.");
var SOCKET_LIST = {};
var io = require('socket.io')(serv,{});
io.sockets.on('connection', function(socket){
socket.id = Math.random();
socket.x = 0;
socket.y = 0;
socket.number = "" + Math.floor(10 * Math.random());
SOCKET_LIST[socket.id] = socket;
socket.on('disconnect',function(){
delete SOCKET_LIST[socket.id];
});
});
setInterval(function(){
var pack = [];
for(var i in SOCKET_LIST){
var socket = SOCKET_LIST[i];
socket.x++;
socket.y++;
pack.push({
x:socket.x,
y:socket.y,
number:socket.number
});
}
for(var i in SOCKET_LIST){
var socket = SOCKET_LIST[i];
socket.emit('newPositions',pack);
}
},1000/25);
client/index.html;
<canvas id="ctx" width="500" height="500" style="border:1px solid #000000;"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script>
var ctx = document.getElementById("ctx").getContext("2d");
ctx.font = '30px Arial';
var socket = io.connect('http://www.myurl:8001', {path: "/socket.io"});
socket.on('newPositions',function(data){
ctx.clearRect(0,0,500,500);
for(var i = 0 ; i < data.length; i++)
ctx.fillText(data[i].number,data[i].x,data[i].y);
});
</script>
It works fine as the code is but only over http. I need this to work over SSL
i need this line to work when its https;
var socket = io.connect('https://www.myurl:8001', {path: "/socket.io"});
How is this possible?
any help is greatly appreciated.
Your server code is only creating an http server, not an https server and since socket.io uses your http server, it will only run on http. http and https servers are different (the https server implements certificate verification and data encryption which is not present with the http server).
To make an https server, change this:
var express = require('express');
var app = express();
var serv = require('http').Server(app);
to this:
const express = require('express');
const app = express();
const options = {...}; // fill in relevant certificate info here
const serv = require('https').createServer(options, app);
And, you will have to fill in the appropriate certificateinfo in the options data structure.
https.createServer() code examples are here.
You can then run your https server on any port you want as long as you connect to it with an https URL and the right port number. You are correct that the default port for an https URL is 443 so if not port number is specified, that's what a browser will attempt to use.
Ok this was a bit embarrasing... the actual problem i had was because of the following.
If you can follow this lol...
So in dreamhost they allow you to run apache and serve content in the usual way. there is a /public folder for this. fairly standard stuff.
Because i'm trying to branch out into being able to use sockets (please don't lecture me on using sockets with PHP... let it go!) So i was using dreamhost which allows a person to proxy a node.js app through a port. eg. port xxxx ends up at thewebsiteurl/whateverfolderyouchoose/
ok so in my node.js i was using express. now in express you can specify routing really easy. For some bizzare reason, i cant be bothered to actually find out why, if you know please enlighten me... i had to put double forward slash in the routing, like so "//whateverroute/". all the examples i was learning from use a single forward slash. eg "/whateverroute/" but that didn't work. if you know why, please tell us. So before i figured this out, i couldn't actually route anything correctly, hence having to use the url with the port number at the end. of course that messes up the https. example, https://www.theurl.com:xxxx wasnt secure, because the node.js app wasnt running an https res req server. Actually i did set up the https node server and thought that was the solution to the problem at first.
So the solution to this bizarre problem was the node.js routing. ofcourse its stupidly complicated because, hey life's like that when your learning from google and not someone who actually knows your exact setup.
What turns out to be funny is, i cant stand node.js. I can see the benefit to using it. But it seems like alot of ball ache for something as simple as what i'm making. Also i have now discovered phone/gap so php actually is ok for what i want to do. Ok so i'm hitting the server way to many times with AJAX requests but it's coping with a few hundred users right now and when it hits the 10'000 mark when the site probably wont work very well, i should be making enough to get a real node.js programmer in to learn from.... hopefully.
I do appreciate the help tho guys.

Azure + Socket IO produces Error 404

NodeJS and socket.io seems to work fine but inspecting the logs I can see an "HTTP Error 404.0 - Not Found" error that I cannot identify why is happening. For example my full url where nodejs is hosted is sample-nodejs.azurewebsites.net
and I get the following error:
Update with more information:
I tried different combinations of setting up the server (using or not express) but I always get the same result.
I initialize my server like this:
var http = require('http');
const PORT = process.env.PORT || 1337;
var server = http.createServer();
var io = require('socket.io')(server);
server.listen(PORT);
io.sockets.on('connection', function(socket)
{
...
});
I used socket.io 1.7.4 through the current latest 2.0.3. and I get the same issue. Debugging the client seems fine but inspecting the Errors from azure "Log stream" I can see randomly (didn't realize a pattern) HTTP 404.0 - Not Found errors and is requesting a url from https://sample-nodejs:80/socket.io/?EIO=3&transport=polling&a..
Isn't the url strange since the full path for the server is sample-nodejs.azurewebsites.net ?

Using VHOST for subdomains on Express

I have 2 separated site (static web and application). I've tried to use Express vhost middleware but I couldn't manage.
For the below codes I configured my hosts file as;
127.0.0.1 localhost
127.0.0.1 process.localhost
my server.js codes
var connect = require('connect')
var express = require('express')
var vhost = require('vhost')
var app = require('./app')
var static = require('./static')
var server = connect()
server
.use(vhost('localhost', static.service))
.use(vhost('process.localhost', app.service))
.listen(1337, function(){
console.log('Server is listening')
})
Then if I write my address bar localhost:1337 static page comes this is good. However, if I write process.localhost:1337 nothing comes.
What should I do?
Edit
If I add the below middleware to my codes when I write the address bar localhost:1337 console write localhost:1337 but is I write process.localhost:1337 console write nothing.
Actually problem was the change of hosts file permissions.
Solution is here;
https://serverfault.com/a/452269/277517

Socket.IO on client side

I am creating a nodejs+express+socket.io server.
Also I created a scaffold via yeoman for my frontend app.
The socket.io server is on port 3000 and my yeoman scaffold http server on 9000.
I have managed to retrieve the socket.io.js from the socket.io server using
<script type="text/javascript" src="http://localhost:3000/socket.io/socket.io.js"></script>
However im having this error:
GET http://localhost:9000/socket.io/?EIO=3&transport=polling&t=1425392110184-42 404 (Not Found)
Why is the socket.io.js polling on port 9000?
Moreover, how can I change this so that it'll poll on 3000 instead?
The socket.io client takes an option URL argument. If not specified, it will connect using the current document origin. This means if the HTML document's URL is http://localhost:9000, then it will connect to http://localhost:9000. Specify it when you connect:
var socket = io('http://localhost:3000');
Instead of
var socket = io();
Okay I solved it by passing the url of the socket.io as parameter to the io() function.
var socket = io('http://localhost:3000');

Resources