Socket.io local network not connecting - node.js

Okay, I have the following setup: https://i.stack.imgur.com/4T9SX.jpg ( If image below is too small )
The problem is that Computer 2 can not connect with socket.io to computer 1.
Yes i included socket.io in computer 2:
Any ideas as to why Computer 2 cannot connect to computer 1 with socket.io whilst ping can?
Extra information:
- Socket.io version 1.4.5
- Both computers are windows 10
- Computer 2 javascript is in Phonegap
- Computer 2 connects via wi-fi, computer 1 via ethernet
Greetings
EDIT
Code from client (computer 2, init is called upon start):
KerstAppHome.prototype.init = function(){
var address = 'http://192.168.2.120:2017';
console.log("Connecting to: " + address);
this.socket = io.connect(address);
this.socket.on('connect', this.proxy(function(){
console.log("Connected to socket!");
this.socketIsConnected = true;
this.socket.on('disconnect', this.proxy(function(){
console.log("Disconnected from socket!")
this.socketIsConnected = false;
}));
this.socket.on('musicBlob', this.proxy(this.onMusicBlobReceived))
}));
};
KerstAppHome.prototype.onMusicBlobReceived = function(musicBlob){
console.log("RECEIVED SOMETHING");
this.audioCtx.decodeAudioData(musicBlob).then(this.proxy(function(audioBuffer) {
var source = this.audioCtx.createBufferSource();
source.buffer = audioBuffer;
source.connect(this.audioCtx.destination);
source.start();
}));
}
Code from server (computer 1):
var port = 2017;
var io = require('socket.io')(port);
console.log("Listening for socket connections on port " + port);
io.on('connection', function (socket) {
console.log("Connection made!");
socket.on('musicBlob', function(musicBlob){
socket.broadcast.emit('musicBlob', musicBlob);
});
});
Relevant code from browser ( computer 1 ):
var socket = io.connect('http://localhost:2017');
var socketIsConnected = false;
socket.on('connect', function(){
console.log("Connected to server!");
socketIsConnected = true;
});
socket.on('disconnect', function(){
console.log("Disconnected from server!")
$scope.socketIsConnected = false;
});
I want to know why computer 2 can't even connect to the server,
The console.log("Connected to socket!"); is not even called
NOTE: If I execute the javascript of the client (computer 2) on computer 1, it works perfectly, makes connection and receives data!
NOTE: I tested it with computer 1 (server) his firewall turned off and it worked perfectly!

please check you firewall settings, or turn it off for few minutes and than try, also make sure both 2 computer should be connected with same lan/wifi. and
allow phonegap, Evented I/O for v8 JavaScript and Secure Socket Tunneling Protocol through Windows Firewall,

As referencing your code in image - you need to check the following things first
What is the exposed url for your nodejs like e.g.localhost:2017 - if you have set it up as locahost - your node server is running as uri of hostname of localhost and ip 127.0.0.1 which cannot be accessed from another machine - if this is the case you need to assign the actual ip to node process 192.168.2.120 (in your case) only then you can access it from another machine
its good to have a namespace to socket,io connect process
are you using windows machine? you need to open network and sharing center - if you are connected to public network - connections will never work - at least the machine running nodejs server should be connected to home or office network
if you are stll facing the issue you can refer the following code for starting the server
const http = require('http');
const url = '192.168.2.120';
var port = 2017;
console.log("Listening for socket connections on port " + port);
var requestListener = function (req, res) {
res.writeHead(200);
res.end('Hello, World!\n');
}
var server = http.createServer(requestListener);
var io = require('socket.io')(server);
server.listen(port,url);
console.log('Server running at:', url+':'+port);
io.on('connection', function (socket) {
console.log("Connection made!");
socket.on('musicBlob', function(musicBlob){
socket.broadcast.emit('musicBlob', musicBlob);
});
This should work out for you.

Related

Cannot GET / using node.js + socket.io to connect client to server

So I am trying to create an indoor location tracker using Bluetooth using the software's node.js and socket.io. I am using a raspberry pi 3 to pickup the RSSI readings and just want the RSSI value from one specific hardware. I have been able to create a connection between my client and server and managed to get the uuid for the specific hardware I want the RSSI value of. However while the connection has been successful I am not getting any of the RSSI values from the pi. Every time I execute the codes below all I get is "Cannot GET / " error whenever I visit my localhost web page.
The following code is what I executed from the pi:
var noble = require('noble');
//replace localhost with your server's IP;
var socket = require('socket.io-client')('http://localhost/scanner');
//replace with your hardware address
var addressToTrack = '7c669d9b2dda';
socket.on('connect', function(){
console.log('connected to server');
});
noble.on('discover', function(peripheral){
if(peripheral.uuid == addressToTrack){
socket.emit('deviceData', {mac: peripheral.uuid, rssi:peripheral.rssi});
}
});
noble.startScanning([], true)
This next code is the code I used to setup my server and how it should receive the information sent from the pi:
var express = require('express');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var scanner = io.of('/scanner');
scanner.on('connection', function(socket) {
console.log('Scanner Connected');
socket.on('message', function(msg) {
//received message from scanner
//do some processing here
});
socket.on('disconnect', function() {
console.log('Scanner Disconnected');
});
});
http.listen(3000, function() {
console.log('listening on *:3000');
});
The following code is taken from https://blog.truthlabs.com/beacon-tracking-with-node-js-and-raspberry-pi-794afa880318 if you're wondering where I am referencing the code from.
I am new to all this so I am trying to understand where the problem is occuring.
You don't have any express route setup for / that's why you're getting: Cannot GET /
Add:
// this should be AFTER socket.io server setup
app.use((req, res) => {
res.send('Hello world');
});
http.listen(3000, function() {
console.log('listening on *:3000');
});
Now every endpoint but socket-io specific endpoints will respond with: hello world
Aside from that, regarding your client side code. You're trying to connect to: http://localhost instead of http://localhost:3000 which the port where your socket.io server is running.

How to run NodeJs SocketIO on server (Centos 7)

I create app with nodejs socket io. It works clearly at localhost (port: 3000). But when i deploy it to my server in there i can run my app on 3000 port but client side throw timeout. How can i solve it?
var fs = require('fs');
var https = require('https');
var options = {
key: fs.readFileSync('ssl.my-key.key'),
cert: fs.readFileSync('ssl.my-cert.crt')
};
var server = https.createServer(options);
var io = require('socket.io').listen(server);
var port = 3000;
const database = require('./Database');
io.on('connection', (socket) => {
socket.on('message', async (msg) => {
// I do some action here.
});
socket.on('disconnect', (msg) => {
// some action in here too
});
});
server.listen(port, () => {
console.log('listening on *:' + port);
});
It seems like your issue is with port forwarding.
In order for your server to be publicly accessed, it needs to have all ports forwarded appropriately. Locally and on the router.
Check this link to learn more about how to port forward on linux: https://linuxacademy.com/guide/11630-internal-port-forwarding-on-linux-using-the-firewall/
And this to learn more about router port forwarding, but this will really depend on your router.
https://www.noip.com/support/knowledgebase/general-port-forwarding-guide/
However, I don't recommend you to take care of hosting on your own machine(s). I
suggest you use Heroku, you can op in for their free servers, you don't need to pay.
More about heroku and NodeJS: https://linuxacademy.com/guide/11630-internal-port-forwarding-on-linux-using-the-firewall/
let we debug your node js app.
1) add some logs on database connection, http.createserver, also where you have to check if not success then catch exception
2) you should have to open port on centOs before start your node js app
3) you should have test you with domain name or ip address
as per you comment you got connection timeout , you mean node js server trying to connect with port 3000 but node not able to connect and its throws error with connection timeout
also send your sample code of your main index file so we can investigate your problen
thanks.

Net Socket Connections in OpenShift

I am trying to create a net socket Nodejs server for my embedded device to send data to on OpenShift.
I am trying to create this simple echo service
var net = require('net');
var HOST = process.env.OPENSHIFT_NODEJS_IP;
var PORT = process.env.OPENSHIFT_NODEJS_PORT || 3000;
console.log('IP:' + HOST + ' Port:' + PORT);
var server = net.createServer(function(connection) {
console.log('client connected');
connection.on('end', function() {console.log('client disconnected');});
connection.write('Hello World!\r\n');
connection.pipe(connection);
});
server.listen(PORT, HOST , function() {
console.log('server is listening');
});
I according to OpenShift's Port Binding Guide I had my client application connect to Port 8000.
For Testing I am using the following code from my desktop machine.
var net = require('net');
var HOST = 'nodejs-myapplication.rhcloud.com';
var PORT = 8000;
var client = net.connect(PORT, HOST, function() {
console.log('connected to server!');
});
client.on('data', function(data) {
console.log(data.toString());
client.end();
});
client.on('end', function() {
console.log('disconnected from server');
});
The Client Scripts gets to Connected to server and gets stuck there itself. Nothing takes place after that.
Now if I open the address nodejs-myapplication.rhcloud.com:8000 in my browser, the NodeJS Server logs a client connected and disconnected, but when the NodeClient is connected the server doesn't show any update. The Node Client just says connected and stays there without doing anything.
If I run the same scripts locally it works fine, ( Locally i use HOst as 127.0.0.1 and port as 3000).
How can I get a TCP Application to connect to the Openshift NodeJS Server?
The Device will be sending ASCII output over the socket eg. $VAR,12,23,21\r\n
I need to be able to read that data, convert it to JSON and send it out to another server.
It has to be loaded on a platform like DigitalOcean with a firewall enabled.
OpenShift doesn't allow custom ports by default so need a workaround for that.

Socket.io and Vagrant can't establish websocket connection

I've got a Vagrant box set up to port-forwards a socket.io application from internal port 5000 to external port 8081; when I try to connect from the client it starts long-polling the connection but I don't see any kind of response from the server and the server app never registers a connection attempt. The connection doesn't fail or return any error response code though, it just returns a 200 code with a blank response.
// Import utilities
var http = require('http'),
socketIO = require('socket.io'),
querystring = require('querystring');
// Init servers/external connections
var server = http.createServer(function baseHandler(req, res) {
// console.log(req.headers);
res.writeHead(200);
res.end(JSON.stringify({
message: 'This server only supports WebSocket connections'
}));
}),
io = socketIO(server);
server.listen(process.env.socket_port || 5000, function() {
var sockets = [];
console.log('App connected');
});
io.on('connection', function (socket) {
console.log('Socket connected');
console.log('Socket in rooms '+ socket.rooms.join(', '));
});
The same app works just fine when I'm trying to connect from the app running directly on my PC, so my code doesn't seem to be the problem here, especially given how it's basically duplicating the basic example in the docs; not really sure how to solve this from here.
This is one of those really stupid bugs which crop up when you're working on two different problems with the same codebase at the same time. Here's the client-side code line which was breaking:
var socket = io('127.0.0.1:8081/?access_token=1d845e53c4b4bd2e235a66fe9c042d75ae8e3c6ae', {path: '/auth/socket.io'});
Note the path key is set to point to a subdirectory, /auth, which is a leftover from my work to get an nginx folder proxying to an internal port which the server was working on.

ECONNREFUSED during socket connect in Node app on Openshift

ECONNREFUSED on socket connect in Node app on openshift servers, works on development machine.
Hi, I am trying to write simple app that needs to make a outgoing socket connection from my server.js ( that came with the pre-installed template). In my express routes i have something like
self.createRoutes = function() {
self.routes = { };
self.routes['/asciimo'] = function(req, res) {
var link = "http://i.imgur.com/kmbjB.png";
res.send("<html><body><img src='" + link + "' /></body></html>");
};
self.routes['/mycfg'] = function(req, res) {
var serviceSocket = new net.Socket();
serviceSocket.connect({port: 443, host:"www.google.com",localAddress:self.ipaddress}, function() {
console.log("connected!!");
});
serviceSocket.on("error", function (e) {
console.log("Could not connect to service " + e);
});
}
}
The self.address is t process.env.OPENSHIFT_NODEJS_IP which is 127.4.217.129 in my case.
I tried the code on my development machine it works fine. But fails with ECONNREFUSED on openshift servers. Any help would be appreciated. Thanks for your time.
The problem was Node version 0.6.25. I created a new app with node verison 0.10 and the same code works fine.
Try something like this instead
var host = process.env.OPENSHIFT_NODEJS_IP;
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({host: host, port: port});
wss.on('connection', function(ws) {
ws.on('message', function(message) {
console.log('received: %s', message);
ws.send(message);
});
ws.send('something');
});
EDIT
My apologies I overlooked that you were making an external connection. After reproducing it locally I was able to connect by removing the localAddress on your Sockect.connect. After looking at the documentation and source a bit this makes sense. Making a connection to google and binding to a local ip won't work due to google not knowing this local ip.

Resources