Unable to close serial port in nodejs - node.js

I'm using node-serialport available here.
Open the port and reading works very well, however I am unable to close the port.
I use the following code for that:
myserialport.on('close', function (err) {
console.log('port closed', err);
});
The callback function is never executed (no console output).
Can anyone, please show me the way?
I would like to be able to close one port and open another if needed or just close the port if user changes the page.
Jan

You can use the .close() method to instruct the serial port to close:
myserialport.close(function (err) {
console.log('port closed', err);
});
.on('close') allows you to add the function as a listener of the 'close' event. But, it will simply wait for the event to occur (to be emitted) rather than instruct it to be done.

Related

Node.js proper socket closing

In case a client timeouts or I want to close the client connection for another reason I would like to close the socket connection properly. By properly I mean that:
The client knows that it shouldn't send any further information
The serverside closes the connection completely (because attackers still might send data to the server which we don't want to read)
At first I thought about using socket.destroy() which will ensure that no more I/O activity will happen. When I tried this I noticed that the client does not get informed about this. Most likely because it can't know that the connection has been closed since nothing has been sent to the client, right?
Because of that I thought emitting socket.end() and immediately after that emitting socket.destroy(). This time the client closed properly, but it triggered the socket.end() event twice. Why is that happening? Is that the proper way of forcing a socketconnection to close or am I missing something?
Server code:
sock.on('destroy', function() {
console.log(sock.remoteAddress + ' has been destroyed');
});
sock.on('end', function() {
console.log(sock.remoteAddress + ' has been half closed');
});
sock.on('timeout', function() {
console.log(sock.remoteAddress + " timed out");
sock.emit('end');
sock.emit('destroy');
});

Receiving specific TCP commands with nodejs and handling them

I have a device in my local that sends JSON data through TCP:
ex. {"cmd": "listactions", "id": 13, "value": 100}
The data is send from 192.168.0.233 on port 8000
(I've checked this with wireshark)
I would like to (with my homeserver) intercept those specific commands with nodejs & send them through with pusher.
I have very little experience with nodejs & can't seem to get this working. I tried the following:
net = require('net');
var server = net.createServer(function(sock) {
sock.setEncoding('utf8');
sock.on('data', function (data) {
// post data to a server so it can be saved and stuff
console.log(data);
// close connection
sock.end();
});
sock.on('error', function (error) {
console.log('******* ERROR ' + error + ' *******');
// close connection
sock.end();
});
});
server.on('error', function (e) {
console.log(e);
});
server.listen(8000, '192.168.0.233', function(){
//success, listening
console.log('Server listening');
});
But it complaints about EADDRNOTAVAIL, from research I've learned that this means the port is in use... Which I don't understand because I'm able to with Wireshark.
What's the correct way to do this?
Wireshark doesn't listen on all ports. It uses a kernel driver (with libpcap or winpcap) to "sniff" data off the wire. That is, it doesn't sit in between anything. It's not a man-in-the-middle. It just receives a copy of data as it is sent along.
Your application needs to listen on that port if you expect it to receive data. You should use netstat to figure out what process is listening on port 8000 and kill it. Then, you can listen on port 8000.
You could in theory use libpcap to get your data but that's crazy. There is a ton of overhead, something has to listen on that port anyway (it's a TCP connection after all), and it's extremely complex to filter out what you want. Basically, you would be reimplementing the network stack. Don't.

Socket.IO: connection to a non-existing namespace

First post, i'll try to be as clear as possible :)
I'm trying to create on Demand namespaces on my SocketIO/NodeJS App.
Basically, the server create a specific namespace for each client.
I need to handle, server side, the case where the client try accessing a non-existing namespace.
The idea is to avoid any unwanted connection server-side, or at least, handle it to force the disconnection.
But while testing, it seems that when i try this, on client Side :
var socket = io("thisNameSpaceDontExist");
socket.on('connect', function(){
window.console.log('connected to server');
})
The 'connect' event won't trigger, which seems perfect !
Doing a console.log on socket, it displays this:
connected: false
disconnected: true
But the main problem, is that, Server Side, it's different, there is an active connection...
While doing some research, i found this issue https://github.com/Automattic/socket.io/issues/1867, still, i'm on the last version at this time: 1.3.5
for information, the socketIOHandler code i'm using:
io.on('connection', function (socket) {
console.log("[SocketIOHandler::Connection] +1");
socket.on('disconnect', function () {
console.log("[SocketIOHandler::Disconnection] -1");
});
});
PS:
Also find some issues and MR claiming the support of dynamic namespaces: https://github.com/Automattic/socket.io/issues/1854, but these are not merged, so i don't really understand the behavior on my code...
Thank you!

How do I make a node.js TCP connection reconnect automatically?

I wrote a TCP client and server in node.js. I can't figure out how to make client reconnect when it disconnects for any reason whatsoever. I understand I have to handle 'close' event, but it's an event that gets fired only when connection gracefully closes. I don't know how to handle network errors when connection just ends because of network issues.
Here's the code that I've so far:
function connect () {
client = new net.Socket();
client.connect(config.port, config.host, function () {
console.log('connected to server');
});
client.on('close', function () {
console.log('dis-connected from server');
connect();
});
client.on('error', ...); // what do I do with this?
client.on('timeout', ...); // what is this event? I don't understand
}
Can anyone explain what do I do in error and timeout case? And how do I know that the network has disconnected and reconnect?
You can probably just leave the error event handler as a no-op/empty function, unless you want to also log the error or something useful. The close event for TCP sockets is always emitted, even after error, so that is why you can ignore it.
Also, close event handlers are passed a boolean had_error argument that indicates whether the socket close was due to error and not a normal connection teardown.
The timeout event is for detecting a loss of traffic between the two endpoints (the timeout used is set with socket.setTimeout().

Socket.io : what happen to the client(socket) after a user is disconnected? Can I/Should I remove it?

I am using socket.io, and I want to know how can I remove the client(socket) after a connection is closed. (In fact, I don't know what is going on after a connection is close, will that socket remained there? Should I remove it? Will it take up memory?)
My code:
socket.No = socketNo++;
io.sockets.on("connection",function(socket){
setInterval(function(){
console.log("Server calling update collection with socket No.",socket.No);
},3000);
//When connection is close()
socket.on("disconnect",function(){
console.log("A user disconnected");
});
})
What happen is that, for example, I disconnect from the server, I find that server is still logging. What can I do so that I can stop it?
Thanks~
In the code above, it is setInterval that is causing the additional logging.
You will need to store off the id returned from setInterval then clear it using clearInterval on a disconnect event.
Something like:
io.sockets.on("connection",function(socket){
var intervalId = setInterval(function(){
console.log("Server calling update collection with socket No.",socket.No);
},3000);
//When connection is close()
socket.on("disconnect",function(){
console.log("A user disconnected");
clearInterval(intervalId);
});
})
Other than that, no need to do anything else with the socket on the server side. It will get garbage collected at some point.

Resources