NodeJS - How to connect to remote PC that runs Node app? - javascript

I have a Nodejs client app, and a Nodejs server app. I use Apollo GraphQL for network.
These communicate fine if run on the same pc. They also work fine if the client is on another pc and server on my pc, over LAN only. They fail to communicate via internet.
My code that works right now:
server:
server.listen(PORT, '0.0.0.0',() ...
client:
const wsLink = new WebSocketLink({
uri: 'ws://192.168.10.41:8081/subscriptions',

Firs of all you must be sure that both nodes have a public IP, otherwise if you are behind a symmetric NAT you will not be able to do that.
After that you can use some of the modules of node, for example UDP(user datagram protocol) to try the connection.
Good Luck

Related

Connecting SOCKET.IO-client (angular) to SOCKET.IO-server (node.js) over https net::ERR_CONNECTION_CLOSED

Our website has been running on an internal test machine where it could be accessed by all computers inside the network.
Now we want to deploy this website on a webserver (Apache2) to make it available to our clients. We want to use https and this is where we encountered a problem.
The Socket.io client can´t connect to the node.js server since switching to https. We are using a signed certificate from a trusted CA. I have tried every solution I could find but none seem to work for our case.
Constructor used with ngx-socket-io in angular:
constructor() {
super({url: 'https://mywebPage.com:8080',options:{secure: true, origin: '*', transport:['websocket']}})
}
Our certificate seems to be valid since it works for our angular page. We are also able to make HTTPS GET/POST requests to our API which is located on the same server.
node.js socket.io server code:
var options = {
key: fs.readFileSync('/etc/apache2/folder/certificate.com.key'),
cert: fs.readFileSync('/etc/apache2/folder/certificate.com.public.crt'),
ca: fs.readFileSync('/etc/apache2/folder/certificate-intermediate.crt'),
requestCert: true
};
let server = require('https').createServer(options);
let io = require('socket.io')(server);
server.listen(8080);
console.log("Server started on Port 8080");
the client tries to connect to the socket-Server but fails and gets the net::ERR_CONNECTION_CLOSED the rest of the web page loads fine and has a valid certificate
We have also tested to see if the port on the web server is accesible and it seems to be open in netstat and nma.
If any more information is needed I am glad to provide.
EDIT: have tested the setup with rejectUnauthorized:false on the client side but that does not change the error.
similar stack overflow questions which i have considered in solving the problem:
socket.io net::ERR_CONNECTION_CLOSED
Setup Server-Server SSL communication using socket.io in node.js
EDIT 2: added requestCert: false, rejectUnauthorized: false into my node.js options.
Now the previous Error has been resolved now:
error during WebSocket handshake: Unexpected response code: 400

Python WebSocket is not working on Raspbery

Running the server and client on mac with localhost everything works fine.
Running the python program (server) on the raspberry pi and try to access it using its url doesn't work.
Python Server:
class Strompreisgenerator:
def __init__(self):
self.ws = websockets.serve(self.echo, 'localhost', 5001)
asyncio.get_event_loop().run_until_complete(self.ws)
asyncio.get_event_loop().run_forever()
async def echo(self, websocket, path):
async for message in websocket:
print(message)
Javascript Client:
var ws = new WebSocket("ws://www.tobiasschmocker.ch:5001");
While trying to instantiate the WebSocket the error "WebSocket network error: The operation couldn’t be completed. Connection refused" occurs in safari.
The Port 5001 is open on RPi. I also tried local IP. I forwarded the Port on my router but still nothing. If i trie other urls i get another error, so i suppose the url is correct but i have no rights somehow.
On my RPi i have ssh enabled, also php, apache, mysql and all the pip packages for my python server.
If you know, where the problem lies, i'd be happy to know. Thank you very much!
Now the websocket is running and available via url from external!
Following is the solution for completeness. All I had to do is:
Update to Python Version 3.6. The websockets package seems to work only from Python Version 3.6. Here's the tutorial I used to install Python 3.6 on my RPi: https://gist.github.com/dschep/24aa61672a2092246eaca2824400d37f
use 0.0.0.0 instead of localhost as host within python. On sudo netstat -lptu in the RPi terminal, I could see that all the other ports (mqtt, ssh, etc) where set to 0.0.0.0 instead of localhost so I just tried and it works.
Having set all that, the websocket is now running. Thanks to #YonatanKiron & #Reto!

Node.js server on local Natted network

I've developed a node.js application while I was in holiday and I was using a not natted wifi connection. Now that I'm back home with my natted wifi I'm not able to access my node js server through the localhost from my phone. I tried accessing it from the local IP but still my server didn't see any connection... Any suggestions?
I'm using socket connections with express and I'm using the 3000 port. I'm on arch linux.

Unable to connect from a different network express.js

I'm experimenting with node.js and express.js.
When I try to connect to my web server from any computer in my network, it works, but then when I try to connect from outside network the connection times out.
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res) {
res.send("Hello World");
});
http.listen(3000, '0.0.0.0', function() {
console.log("Listening on port 3000!");
});
I just tested your code and I'm able to access the server from outside my local network by navigating to:
http://173.0.[my].[ip]:3000
So the code is correct. It could be that you need to open the port 3000 to the outside world. Here's how it can be accomplished.
Through your router admin interface
Here's mine for example:
Where 192.168.1.130 is the local IP of the PC I'm running the http server on.
Don't forget to click the Save settings button in that interface to apply the changes.
Using a tool like ngrok (mentioned by eddiezane)
Install ngrok through their website or without leaving the command prompt, with the ngrok node wrapper.
npm install ngrok -g
Start your http server and then run:
ngrok http 3000
Navigate to one of the url in front of Forwarding:
The free version is more for a quick test and less as a definitive way to expose a service in a production environnement since every time you restart ngrok, a new user-hostile url is given to you.
Other possible problems
It could also be that you need to add an exception to the firewall (if on windows).
To add to Emile's answer, I would check out ngrok which is an awesome tool that generates you a publicly accessible URL for a port on your local machine.
Here's a good blog post on it my buddy wrote.

getting "websocket connection invalid" error using socket.io on an ec2 instance?

I have this web app written with express and socket.io using node.js, the app works brillantly on localhost, but when i push to my ec2 server, it connects for like 20 seconds then disconnects, and then connects again etc...
giving me the error on the node console as
warn - websocket connection invalid
info - transport end
SERVER
app = express()
server = http.createServer(app)
io = require('socket.io').listen(server)
CLIENT
socket = io.connect()
I know the problem is not with my code, because I fully tested the web app on localhost, so the only problem is where this code is running, which is my ec2 instance?
There could be many possible reasons you can get this error:
You are using browser that partially or does not support websockets. You can check if your browser supports websockets here.
Using proxy that does not support websocket. If there is some server(load balancer) between your client and your node server that does not support websocket.
You are using socket.io version 0.9.1/0.9.1-1. This behaviour is a reported bug for this version. So upgrade to latest socket.io version which is 0.9.14.
Browser connectivity is firewalled/blocked.
Code related problem.
Make sure you're using latest versions of node, express and socket.io on your ec2. Also, provide some data about currently used versions both on your local machine and on ec2 instance.
Running on your local machine you don't have to deal with network latency, NAT issues, or firewalls. Running on EC2 you have all of those.
Web Sockets are relatively new and unstable. So to begin with be sure you're running the latest versions (and let us know what they are). Perhaps the version of socket.io installed on your local machine is different than the version installed in your EC2 server.
If there is no activity during those 20 seconds before losing the connection, one possibility is that keep-alive is set too low.
See https://groups.google.com/forum/?fromgroups=#!topic/socket_io/RUv70BguZ-U for a similar problem. The solution there was to use heartbeat to keep the connection open.
A bit more on socket.io heartbeats if you're not already using them:
Advantage/disadvantage of using socketio heartbeats

Categories

Resources