Socket.io client doesn't connect to server - node.js

I have developed a simple chat using socket.io on a vagrant environment and it works correctly.
When I try to run the chat on the production environment, the nodejs/socket.io server runs but the client doesn't even fire the connect event.
The only thing I've modified is, in the client side:
var socket = io.connect('http://localhost:3000');
to:
var socket = io.connect('http://ip_address:3000');
This is the server code:
var app = require('http').createServer(handler);
var io = require('socket.io')(app);
app.listen(3000, function() {
console.log('Server is running');
});
function handler(req, res) {
res.writeHead(200);
res.end('');
}
io.on('connection', function(socket) {
socket.on('subscribe', function() {
console.log('subscribe request has arrived');
console.log(socket.id);
});
});

If it worked locally and stopped working after deployment, it's probably a network issue - firewall, blocked port, linux enforcing or something of that sort.
To find the source, go to the host server and try connecting the port
telnet 127.0.0.1 3000
Did you get 'Connection refused' error? if so which server is running the code? make sure firewall service is either off or with exceptions for port 3000. on linux check enforcing .
If the connection succeed, test the connection from your local pc
telnet ip_address 3000
If it fails than test access to external service (for example portquiz.net) This way you will know if the issue is with your local pc or network, or the remove server.

Related

Socket.IO with HTTPS over apache present?

I have a domain name.
I have a Raspberry Pi as a web-server.
I've edited domain's A record to point it to my server's IP.
Via letsencrypt I got myself a certificate and now website works on https protocol (keeping http on for debug purposes)
I'm working on a messenger app that uses socket.io but using apache+php for low level stuff
So basically apache listens to 80 and 443 and nodejs listens to 3000
Obviously if I visit my site over http - everything works fine and both server and client register connections.
If I visit it over https - Chrome throws net::ERR_CONNECTION_CLOSED error (in console when trying to connect to socket.io over port 3000. Site itself loads normally).
Client:
var socket = new io(window.location.host+":3000", { secure: true });
socket.on("connect", function() {
console.log('success')
});
Server:
const io = require("socket.io");
const server = io.listen(3000);
console.log("Server started");
server.on("connection", function (socket) {
console.log("+USER");
socket.emit("hello", "Connected");
});
I really don't want to use express or anything else for that matter to keep everything as small as possible, especially since I already have a web-server running.
How to properly set it up so users could connect to my socket.io server on port 3000 when they visit the site via https protocol?
Update:
From what it seems I think it's a CORS-thing type of a problem. User visiting website over https is trying to connect to an unsecured port (this case 3000) even though it's the same domain? I'd think that would be a no-no for a lot if not all browsers.
A solution comes to mind to just move the whole thing from apache to a nodejs server module and assign manually port 3000 as a secure one via https module but I've no idea how to do it, and I'd really want to keep my apache as a web-server because at least I'm more familiar with it than anything else.
Well I ended up creating a separate https server that I assume socket.io listens to (?)
Good thing I still have my apache as a main server. I partially answered my question using this post
https://serverfault.com/questions/745248/socket-io-combined-with-apache-ssl-server
Server
const fs = require("fs");
const https = require("https");
var options = {
key: fs.readFileSync('/etc/letsencrypt/live/example.com/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/example.com/fullchain.pem')
};
var server = https.createServer(options);
server.listen(3000);
var io = require('socket.io').listen(server);
console.log("Server started");
io.on("connection", function (socket) {
console.log("+USER");
socket.emit("hello", "Connected");
socket.on("disconnect", () => {
console.log("-USER");
})
});
Client
var s = new io("https://example.com:3000", { secure: true } );
Hope this is the right way to do it

nodejs websockets connection from localhost works but remote doesnt

I'm running a simple websocket server in nodejs
const WebSocket = require('ws');
const wss = new WebSocket.Server({ host: '0.0.0.0', port: 13000 });
wss.on('connection', function connection(ws) {
console.log("new connection");
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.on('error', function(e) {
console.log('error', e);
});
ws.on('close', function(e) {
console.log('close', e);
});
ws.send('something');
});
I can connect to the server using:
s=new WebSocket('ws://localhost:13000')
and everything is fine. But if I try to connect from another computer:
s=new WebSocket('ws://serveripaddress:13000')
The server shows
new connection
close 1006
So I know that the client connects, but it then immediately disconnects. I am totally lost here, don't know how to diagnose my problem. Any ideas?
UPDATE
These scenarios work:
two ec2 instances: works
two linux VMs communicating over a host-only network: works
And these fail:
windows host machine and VM (host only network): fail
an ec2 instance and one of my VM's: fail
Here's the weird part, if I make a simple socket server using 'net', ALL scenarios above work! So it seems like its still a networking issue (since websockets work in some scenarios) but it is a networking issue specific to websockets (because socket server works where websocket doesnt)!
I dont have access to the firewall that my windows host machine is on so if that's the issue then I'm stuck. But I will try this all on a different host machine where I have access to the firewall.
But if it was the firewall, I would except it to work between the windows host and the VM because they are on their own virtual network...

Server showing multiple client connection (net nodejs)

I am trying to make a server which listens on a internet facing port and forwards incoming http requests to an internal express server listening at another port. Following is the relevant part of the code I'm using.
var net = require('net');
var server = net.createServer();
server.listen(addr.from[3], addr.from[2], function(){
console.log('Server listening');
});
server.on('connection',function(from){
console.log('Client connected from '+ from.remoteAddress);
var to = net.createConnection({
host: addr.to[2],
port: addr.to[3]
});
from.pipe(to);
to.pipe(from);
from.on('error',function(err){
winston.error('Error at unix box'+err);
to.end();
});
to.on('error',function(err){
winston.error('Error at middleware server'+err);
from.end();
});
from.on('end',function(){
console.log('Client disconnected ');
to.end();
});
to.on('end',function(){
console.log('Middleware disconnected');
from.end();
});
});
The problem I'm encountering is that, when I open "ip:port" in the browser (which would be the internet facing port) I'm getting messages multiple "client connected from xxxxxx" msgs on the console. Can anyone help me understand why this is happening?
Whenever browser connects to a website it usually makes two requests: normal and to retrieve favicon.
Funny thing, is that the favicon request is not even displayed in browser developer tools.
To verify, you need to extract the request made, print it to server, and then observe why you get multiple requests. For that, connection might be too early, try hooking request event instead:
server.on('request', funtion(req, res) { console.log(req.url); });

Adobe AIR- connection issues with socket.io

I have a desktop app in Adobe Air (flex).
I have used flashSocket.io library in my app to communicate with socket.io on node.js server.
It works perfectly for most of the clients.
But for some random client the flex app is not able to create a connection with the socket.io server. It constantly throws connection error and close error on flex. The clients are not behind any firewalls or proxy server.
The console has warning like
Web Socket Connection Invalid
I guess this for those clients who are not able to connect.
Since its working for majority of the users i don't know where should i look into. Also, i am unable to reproduce this on my side.
Here's the Server Code:
var io = require('socket.io').listen(app);
app.listen(8080, function() {
console.log('%s listening at %s', app.name, app.url);
});
io.configure(function() {
io.set('transports', ['flashsocket']);
io.set('flash policy port', 843);
});
Flex code:
socket = new FlashSocket("http://domain.com:8080/");
socket.addEventListener(FlashSocketEvent.CONNECT, onConnect);
socket.addEventListener(FlashSocketEvent.MESSAGE, onMessage);
socket.addEventListener(FlashSocketEvent.CLOSE, onDisconnect); //only close and connect_error event is always fired for certain clients
socket.addEventListener(FlashSocketEvent.CONNECT_ERROR, onConnectError);
Any help would be highly appreciated.
Use a different port, we're using 443.

Node.js chat app doesn't load

I just created a node.js chat app.. but the app doesn't load.
The code is very basic node.js chat app:
// Load the TCP Library
var net = require('net');
// Keep track of the chat clients
var clients = [];
// Start a TCP Server
net.createServer(function (client) {
console.log("Connected!");
clients.push(client);
client.on('data', function (data) {
clients.forEach(function (client) {
client.write(data);
});
});
}).listen(5000);
// Put a friendly message on the terminal of the server.
console.log("Chat server is running\n");
After I compile it, I write in the chrome browser localhost:5000 but the page is keep loading and never finish.
However, the following code works perfectly:
// Load the TCP Library
net = require('net');
// Start a TCP Server
net.createServer(function (client) {
client.write("Hello World");
client.end();
}).listen(5000);
I run Windows 7 64 bit on my computer, and I'm using chrome.
Thanks in Advance!
You are creating a TCP/IP server by using the net module, but you are accessing it using the http protocol using your web browser.
This does not match each other.
Try to connect to your server using telnet, e.g., and everything should be fine.
Alternatively, if you want to be able to connect using your webbrowser, you need to use the http module instead of the net module.
The net library if for TCP, not for HTTP. If you use TCS you should be able to access your chat with telnet but not with the browser.
This is an example on how write one for HTTP (from http://nodejs.org/)
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
Don't test with browser when opening tcp connection.
Simply test with
telnet localhost 5000 in your console.

Resources