Node server cannot open specified port - node.js

I am trying to write a program that allows me to communicate with a device using the serial port. To do so, I am using the following code :
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var SerialPort = require("serialport");
var port = new SerialPort("/dev/ttyS1");
app.use(express.static(__dirname+"/../.."));
app.use(express.static(__dirname+"/../../../bower_components/"));
io.on('connection', function(socket) {
console.log('new connection');
socket.on('message', function (message) {
//console.log('Position : ' + message); //envoi port ... à la place
//port.on('open', function() {
port.write(message, function(err) {
if (err) {
return console.log('Error on write: ', err.message);
}
});
//});
});
});
server.listen(8080, function() {
console.log('server up and running at 8080 port');
});
However, the issue here is that the port never seems to open, but the value we are supposed to send is still printed in the console,and the /dev/tty (which represents the console) is opened, but the /dev/ttyS1 do not get opened. The following screenshot is obtained after executing
sudo strace -e open,write node server.js
According to the documentation, the port is supposed to open automatically when we instantiate the SerialPort object.
So, are there any issues in my code or is there any better way to do this ?

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
});

Socket.io with Adonis.js

I am using Adonis 4.1.0 and Adonis-websocket is only been available for v3. Can anyone tell me workaround for using socket.io with Adonis 4.1.0?
apparently they have been working on this not long ago, it was based on socket.io but because of some issues like memory leaks and others, they decided to use websockets directly instead, check these discussions :
https://github.com/adonisjs/discussion/issues/51
https://forum.adonisjs.com/t/integrating-socket-io-with-adonis-4/519
have you tried using socket.io without relying on Adonis ? ,
something like :
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
But you should be able to do this with Adonis by now according to : https://github.com/adonisjs/adonis-websocket-protocol
Example :
const filereader = require('simple-filereader')
const msgpack = require('msgpack-lite')
const packets = require('#adonisjs/websocket-packets')
const client = new WebSocket('ws://localhost:3000/adonis-ws')
client.onopen = function () {
// TCP connection created
}
client.onerror = function () {
// TCP connection error
}
client.onmessage = function (message) {
filereader(message, function (error, payload) {
const packet = msgpack.decode(payload)
handlePacket(packet)
})
}
function handlePacket (packet) {
if (packets.isOpenPacket(packet)) {
console.log('Server ack connection. Make channel subscriptions now')
}
if (packets.isJoinAck(packet)) {
console.log('subscription created for %s', packet.d.topic)
}
}
check this for broadcast examples using WS : https://github.com/websockets/ws#broadcast-example
Create start/socket.js file and paste following code inside it.
const Server = use('Server')
const io = use('socket.io')(Server.getInstance())
io.on('connection', function (socket) {
console.log(socket.id)
})
From Virk Himself in this forum:https://forum.adonisjs.com/t/integrating-socket-io-with-adonis-4/519
create a standalone socket io configuration file in start/socket.js
const io = require('socket.io')();
io.listen(3000);
io.on('connection', function (socket) {
console.log(socket.id)
})
to start your socket io server you can configure your server.js as below
new Ignitor(require('#adonisjs/fold'))
.appRoot(__dirname)
.preLoad('start/socket') //path of socket.js
.fireHttpServer()
.catch(console.error)
now when you start your server then it will start along with socket io

socket.io not working node.js

I am not able to run socket.io code in node.js, console.log() is also not displaying when running the code. Below is the code.
app.js
var express = require('express');
var http = require('http');
var app = express();
app.set('port', process.env.PORT || 3000);
app.post('/testStream',test.testStream);
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
module.exports.appServer = server;
and I have created a test.js file where I am accessing this exported variable appServer.
var server = require('../app.js');
exports.testStream = function(req,res){
var io = require('socket.io').listen(server.appServer);
io.on('connection',function(socket){
console.log("in socket");
fs.readFile('E:/temp/testimg.png',function(err,buf){
socket.emit('image',{image: true,buffer: buf});
console.log("test image");
});
})
}
when the code runs it stucks and not showing the console.logs(). What I am doing wrong over here. Any help is very much appreciated.
I would suggest following the code structure as suggested in socket.io docs.
Also, you should not be calling io.listen or io.on('connection') inside your testStream express middleware. These are things you should only be doing once, and ideally they should happen during startup, inside app.js and not in reaction to a POST request. In fact, I'm not sure what the purpose of your testStream middleware is, its not even returning any response (eg res.end())
If you want to handle socket connections in a separate module you can, but instead of exporting your app's server the way you are, try passing the io instance as variable to your submodule. In short, try this:
app.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var test = require('./test')(io);
app.set('port', process.env.PORT || 3000);
server.listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
test.js
module.exports = function(io) {
io.on('connection', function(socket) {
console.log("in socket");
fs.readFile('E:/temp/testimg.png', function(err, buf) {
socket.emit('image', {
image: true,
buffer: buf
});
console.log("test image");
});
});
};

Can you send a unix domain file descriptor over another unix domain socket in node.js?

In Node.js.
Is it possible to send a unix domain socket file descriptor over already established unix domain socket ?
I have the following example but I am not sure how and if it's even possible to receive the file descriptor on the other end in usable form.
currently getting file descriptor type error on the server side
In the example I have the client connecting to the server side via unix socket and that works fine, then once the connection is established I try to create a new server with new unix socket and pass that file descriptor to the server so server can use it.
Server side:
var net = require('net');
var socket = '/tmp/testing.node.sock';
var fs = require('fs');
if (fs.existsSync(socket)) {
fs.unlinkSync(socket);
}
var server = net.createServer(function(c) {
console.log('server connected');
c.on('end', function() {
console.log('server disconnected');
});
c.on('error', function(e) {
console.log(e);
});
c.on('data', function(data) {
console.log("data received");
console.log(data.toString());
// creating new socket with passed fd
var newsock = new net.Socket({fd:data}); // how do I convert it here to file descriptor - if even possible
console.log(newsock);
});
});
server.listen(socket, function() {
console.log('server bound');
});
client side:
var net = require('net');
var socket = '/host/testing.node.sock';
var fs = require('fs');
client = net.connect({path: socket}, function () {
// here we create a new server that we want the fd passed to other server
var newSock = '/tmp/testing.node.sock';
if (fs.existsSync(newSock)) {
fs.unlinkSync(newSock);
}
// create a new server
var server = net.createServer(function (c) { //'connection' listener
console.log('server connected');
c.on('end', function () {
console.log('server disconnected');
});
c.on('error', function (e) {
console.log(e);
});
c.on('data', function (data) {
console.log("data received");
console.log(data);
});
});
server.listen(newSock, function () { //'listening' listener
console.log('server bound');
console.log(server);
// here we want to pass the new fd
client.write(new Buffer(server._handle.fd));
});
});
Thanks
Back in node v0.4 this functionality existed for both sending and receiving but it was later removed. You'll have to write your own binding to allow you to send/receive file descriptors on an existing fd (your unix domain socket, whose fd should be accessible in node IIRC). Here are some links to get you started.
As described in https://github.com/nodejs/help/issues/345,
Node doesn't support this anymore because there's no way to do it on Windows. But this package provides a UNIX socket API that can send file descriptors: https://www.npmjs.com/package/usocket

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