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

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.

Related

Not understanding why I am not receiving any rssi data from my raspberry pi 3 to my server

I am having problems trying to display the RSSI values from my raspberry pi 3 to show on my server.
Connection Success as you can see by the picture I have been able to successfully connect my client and server but no rssi data are showing.
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:3000/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 forgive if I continuously ask for clarifications.
You're missing a listener for deviceData on the server, which is the event you're emitting from the client.
socket.on('deviceData', function(msg) {
//received message from scanner
//do some processing here
});

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.

Why is my connection of a NodeJS server (Sails) to another NodeJS Server (Express4) using Socket.IO failing?

I am trying to connect my Node.JS (written using Sails.JS) app to another Node.JS server (Express4 / Socket.io) using socket.io-client.
My Sails Service app/services/Watcher.js looks like
var client = require('../../node_modules/sails/node_modules/socket.io/node_modules/socket.io-client');
// callback of the form function(socket)
exports.connect = function(callback) {
sails.log.debug("will connect socket to", sails.config.watcher.uri, "with Socket.io-client version", client.version);
var socket = client.connect(sails.config.watcher.uri);
socket.on('connect', function(){
sails.log.debug("connected");
socket.on('disconnect', function(){
sails.log.debug("Disconnected");
});
socket.on('error', function(err){
sails.log.debug("Could not connect", err);
});
callback(socket);
});
};
This is invoked from config/bootstrap.js as follows:
Watcher.connect(function(socket){
sails.log.debug("Connected watcher to relay with socket", socket);
});
On the Express side my server relay.js is as simple as:
var app = require('express')(),
http = require('http').Server(app),
io = require('socket.io').listen(http),
port = process.env.RELAY_PORT || 8000;
app.get('/', function(req, res) {
var response = {message: "some response"}; // to be implemented.
res.json(response);
});
http.listen(port, function () {
console.log("Relay listening on port " + port);
});
io.sockets.on('connection', function (socket) {
console.log("Connection opened", socket);
socket.on('disconnect', function () {
console.log("Socket disconnected");
});
});
When I run node relay it dutifully reports
Relay listening on port 8000
When I sails lift my other server it dutifully reports
will connect socket to http://localhost:8000 with Socket.io-client version 0.9.16
But I never see an actual connection.
If I point a browser at localhost:8000 I get the {"message":"some response"} JSON response I expect.
Why isn't my relay server accepting a connection from my socker.io-client app?
The issue here is probably that you're trying to re-use the
socket.io-client from inside of Sails. In general, if you're require()-ing dependencies of Sails directly in your project, you're heading in the wrong direction. In this case, socket.io-client caches configurations and connections, so your require isn't getting a fresh copy.
Instead, do
npm install socket.io-client#~0.9.16 --save
in your project and require with
var client = require('socket.io-client');
that'll give you a fresh copy of the socket client to work with, and avoid any conflicts with the Sails core's version.

How to connect two node.js servers with websockets?

Here's my problem:
I have server A, running node.js and using socket.io for communicating with clients (web browsers). This all is running fine and dandy.
However, now that I have server B, which also needs to connect to server A through websockets, I have hit a wall. None of the node.js websocket clients I've found won't work with the socket.io on the server A.
So, this is the case I'm striving for:
.--------. .----------. .----------.
| CLIENT | <--> | SERVER A | <--> | SERVER B |
'--------' '----------' '----------'
Client-server A connection is done through socket.io
Now, Server B (running node.js) should connect to server A via websocket (in order to go through port 80). But...
Even the example code in socket.io-client module doesn't work... :/
// Connect to server
var socket = new io.Socket('localhost', {port: 8080});
socket.connect();
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected.');
});
The code just passes without any errors and execution ends after few seconds.
Update: Code samples
Server (which works just fine) looks like this:
// Load requirements
var http = require('http'),
io = require('socket.io');
// Create server & socket
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Aw, snap! 404</h1>');
});
server.listen(8080);
io = io.listen(server);
// Add a connect listener
io.sockets.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
Client looks like this
console.log('1');
// Connect to server
var io = require('socket.io-client')
var socket = new io.Socket('localhost', {port: 8080});
socket.connect();
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
1, 2 and 3 prints out just fine, no errors, and few seconds later the process just exits
Also, server A doesn't output anything to the log, even though I have the socket.io logging set on "everything".
For future people:
Here is 2 very simple Node.js apps that use socket.io to connect, send and receive messages between each other.
Required package is:
npm install socket.io
Node-App-1 server.js:
var io = require('socket.io').listen(3000);
io.on('connection', function (socket) {
console.log('connected:', socket.client.id);
socket.on('serverEvent', function (data) {
console.log('new message from client:', data);
});
setInterval(function () {
socket.emit('clientEvent', Math.random());
console.log('message sent to the clients');
}, 3000);
});
Node-App-2 client.js:
var io = require('socket.io-client');
var socket = io.connect("http://localhost:3000/", {
reconnection: true
});
socket.on('connect', function () {
console.log('connected to localhost:3000');
socket.on('clientEvent', function (data) {
console.log('message from the server:', data);
socket.emit('serverEvent', "thanks server! for sending '" + data + "'");
});
});
Turns out I was using old examples, for some reason, even though I triple checked them. Well, doh.
Also, it turned out that the socket.io-client is broken on latest Node (6.x.x). Managed to find an update from github for it, replaced the files and yay, everything's working!
Edit: Unfortunately I didn't save any links to working examples but after quickly skimming through the code it seems that the only changes were to the client code, which now looks like this:
console.log('1');
// Connect to server
var io = require('socket.io-client')
var socket = io.connect('localhost:8080', {reconnect: true});
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
Here is a snippet of code I wrote, it's using socket.io 1.0.6 and socket.io-client 1.0.6. The case is the following:
Server A (Socket.io Client) <---> Server B (Socket.io Server)
Server B (Server):
// Load requirements
var http = require('http'),
io = require('socket.io');
// Create server & socket
var server = http.createServer(function(req, res)
{
// Send HTML headers and message
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Aw, snap! 404</h1>');
});
server.listen(8080);
io = io.listen(server);
// Add a connect listener
io.sockets.on('connection', function(socket)
{
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
Server A (Client):
console.log('1');
// Connect to server
var io = require('socket.io-client');
var socket = io.connect('http://localhost:8080', {reconnect: true});
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
If I'm using localhost:8080 only on the client server it doesn't connect.

Resources