Node.js - Distinguish between server connect and disconnect on 'connection' event - javascript

I'm creating a server in my Node.js application with net.createServer.
I add an event listener to the "connection"-event to be able to determine when a connection has been established. All well so far.
The problem is that when I disconnect it seems to trigger the "connection"-event again! And there is no "disconnect" event, so I don't know how to know if it is connected or disconnected!
const server = createServer({ allowHalfOpen: true }, (socket) => {
this._socket.on("data", (buffer) => {
// ...
});
this._socket.on("end", () => {
// ...
});
server.on("connection", () => {
console.log("Connected or Disconnected!")
});
How can I determine if the connection is established or ended?
I would like to avoid having a flag keeping track of the state if possible.
Thanks!

server.on("close", () => {
console.log("Disconnected!")
});
https://nodejs.org/api/http.html#http_event_close

Within the connection listening event, there is a listening event for disconnections:
var clients = [];
server.on('connection', (socket) => {
// add client
clients.push({id:15, name:'client15'});
socket.on('disconnect', () => {
// first search client and remove
});
});
Now the next question would be: how do I know which person disconnected?
The answer to this question is more than putting logic to the process and you can create a global variable for save client, when the person starts session or connects to the socket, it is registered in that variable and when it is disconnected it must be taken out of said variables, this is not ma than an example but there may be better ways.

So my naive approach to this issue that seems to work is to use getConnections, which will increase on every connection event, and see if it is even or uneven to be able to determine if it is connected or disconnected:
server.on("connection", () => {
server.getConnections((e, c) => {
if (c % 2 === 0) {
// Disconnected
} else {
// Connected
}
});
It does not feel like a good solution, but maybe good enough until someone can show me a better way.

Related

How to terminate a WebSocket connection?

Is it possible to terminate a websocket connection from server without closing the entire server? If it is then, how can I achieve it?
Note: I'm using NodeJS as back-end and 'ws' websocket module.
So because of some sort of omission in the documentation regarding ws.close() and ws.terminate() I think the solutions in provided answers won't close the sockets gracefully in some cases, thus keeping them hanging in the Event Loop.
Compare the next two methods of ws package:
ws.close():
Initializes close handshake, sending close frame to the peer and awaiting to receive close frame from the peer, after that sending FIN packet in attempt to perform a clean socket close. When answer received, the socket is destroyed. However, there is a closeTimeout that will destroy socket only as a worst case scenario, and it potentially could keep socket for additional 30 seconds, preventing the graceful exit with your custom timeout:
// ws/lib/WebSocket.js:21
const closeTimeout = 30 * 1000; // Allow 30 seconds to terminate the connection cleanly.
ws.terminate():
Forcibly destroys the socket without closing frames or fin packets exchange, and does it instantly, without any timeout.
Hard shutdown
Considering all of the above, the "hard landing" scenario would be as follows:
wss.clients.forEach((socket) => {
// Soft close
socket.close();
process.nextTick(() => {
if ([socket.OPEN, socket.CLOSING].includes(socket.readyState)) {
// Socket still hangs, hard close
socket.terminate();
}
});
});
Soft shutdown
You can give your clients some time to respond, if you could allow yourself to wait for a while (but not 30 seconds):
// First sweep, soft close
wss.clients.forEach((socket) => {
socket.close();
});
setTimeout(() => {
// Second sweep, hard close
// for everyone who's left
wss.clients.forEach((socket) => {
if ([socket.OPEN, socket.CLOSING].includes(socket.readyState)) {
socket.terminate();
}
});
}, 10000);
Important: proper execution of close() method will emit 1000 close code for close event, while terminate() will signal abnormal close with 1006 (MDN WebSocket Close event).
If you want to kick ALL clients without closing the server you can do this:
for(const client of wss.clients)
{
client.close();
}
you can also filter wss.clients too if you want to look for one in particular. If you want to kick a client as part of the connection logic (i.e. it sends bad data etc), you can do this:
let WebSocketServer = require("ws").Server;
let wss = new WebSocketServer ({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.send('something');
ws.close(); // <- this closes the connection from the server
});
and with a basic client
"use strict";
const WebSocket = require("ws");
let ws = new WebSocket("ws://localhost:8080");
ws.onopen = () => {
console.log("opened");
};
ws.onmessage = (m) => {
console.log(m.data);
};
ws.onclose = () => {
console.log("closed");
};
you'll get:
d:/example/node client
opened
something
closed
According to the ws documentation, you need to call websocket.close() to terminate a connection.
let server = new WebSocketServer(options);
server.on('connection', ws => {
ws.close(); //terminate this connection
});
Just use ws.close() in this way.
var socketServer = new WebSocketServer();
socketServer.on('connection', function (ws) {
ws.close(); //Close connecton for connected client ws
});
If you use var client = net.createConnection() to create the socket you can use client.destroy() to destroy it.
With ws it should be:
var server = new WebSocketServer();
server.on('connection', function (socket) {
// Do something and then
socket.close(); //quit this connection
});

RxJs avoid external state but still access previous values

I'm using RxJs to listen to a amqp queu (not really relevant).
I have a function createConnection that returns an Observable that emits the new connection object. Once I have a connection, I want to send messages through it every 1000ms and after 10 messages I want to close the connection.
I'm trying to avoid external state, but if I don't store the connection in an external variable, how can I close it? See I begin with the connection, then flatMap and push messages, so after a few chains I no longer have the connection object.
This is no my flow but imagine something like this:
createConnection()
.flatMap(connection => connection.createChannel())
.flatMap(channel => channel.send(message))
.do(console.log)
.subscribe(connection => connection.close()) <--- obviously connection isn't here
Now I understand that it's stupid to do that, but now how do I access the connection? I could of course begin with var connection = createConnection()
and later on somehow join that. But how do I do this? I don't even know how to ask this question properly. Bottomline, what I have is an observable, that emits a connection, after the connection is opened I want an observable that emits messages every 1000ms (with a take(10)), then close the connection
The direct answer to your question is "you can carry it through each step". For example, you can replace this line
.flatMap(connection => connection.createChannel())
with this one:
.flatMap(connection => ({ connection: connection, channel: connection.createChannel() }))
and retain access to the connection all the way down.
But there's another way to do what you want to do. Let's assume your createConnection and createChannel functions look something like this:
function createConnection() {
return Rx.Observable.create(observer => {
console.log('creating connection');
const connection = {
createChannel: () => createChannel(),
close: () => console.log('disposing connection')
};
observer.onNext(connection);
return Rx.Disposable.create(() => connection.close());
});
}
function createChannel() {
return Rx.Observable.create(observer => {
const channel = {
send: x => console.log('sending message: ' + x)
};
observer.onNext(channel);
// assuming no cleanup here, don't need to return disposable
});
}
createConnection (and createChannel, but we'll focus on the former) returns a cold observable; each subscriber will get their own connection stream containing a single connection, and when that subscription expires, the dispose logic will be called automatically.
This allows you to do something like this:
const subscription = createConnection()
.flatMap(connection => connection.createChannel())
.flatMap(channel => Rx.Observable.interval(1000).map(i => ({ channel: channel, data: i })))
.take(10)
.subscribe(x => x.channel.send(x.data))
;
You don't actually have to dispose the subscription for cleanup to occur; after take(10) is satisfied, the whole chain will finish and cleanup will be triggered. The only reason you'd need to call dispose on the subscription explicitly is if you wanted to tear things down before the 10 1000ms intervals were up.
Note that this solution also contains an instance of the direct answer to your question: we cart the channel down the line so we can use it in the onNext lambda passed to the subscribe call (which is customarily where such code would appear).
Here's the whole thing working: https://jsbin.com/korihe/3/edit?js,console,output
This code gave me a error because flatmap wait for a observable<(T)> and ({ connection: connection, channel: connection.createChannel() }) it's a Object.
.flatMap(connection => ({ connection: connection, channel: connection.createChannel() }))
instead you can use the combineLatest operator
.flatMap(connection => Observable.combineLatest( Observable.of(connection), connection.createChannel(), (connection, channel) => {
... code ....
});

How to properly close a Node.js TCP server?

I couldn't find a clear answer on Google or SO.
I know a net.Server instance has a close method that doesn't allow any more clients in. But it doesn't disconnect clients already connected. How can I achieve that?
I know how this can be done with Http, I guess I'm asking if it's the same with Tcp or if it's different.
With Http, I'd do something like this:
var http = require("http");
var clients = [];
var server = http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("You sent a request.");
});
server.on("connection", function(socket) {
socket.write("You connected.");
clients.push(socket);
});
// .. later when I want to close
server.close();
clients.forEach(function(client) {
client.destroy();
});
Is it the same for Tcp? Or should I do anything differently?
Since no answer was provided, here is an example of how to open and (hard) close a server in node.js:
Create the server:
var net = require('net');
var clients = [];
var server = net.createServer();
server.on('connection', function (socket) {
clients.push(socket);
console.log('client connect, count: ', clients.length);
socket.on('close', function () {
clients.splice(clients.indexOf(socket), 1);
});
});
server.listen(8194);
Close the server:
// destroy all clients (this will emit the 'close' event above)
for (var i in clients) {
clients[i].destroy();
}
server.close(function () {
console.log('server closed.');
server.unref();
});
Update: Since using the above code, I've ran into an issue that close will leave the port open (TIME_WAIT in Windows). Since I'm intentionally closing the connection, I'm using unref as it appears to fully close the tcp server, though I'm not 100% if this is the correct way of closing the connection.
I am using NodeJS v16.13.2 ... When the process containing the server code exits, all clients connection are closed/destroyed by default.
I came here to find out how I could listen for a server.("exit", myTaskCallback), since I wanted to delete some files while exiting the server. But the answer I have found is that such event does not exists. I had to listen to process.on('exit', myTaskCallback) to do the job.
sock.end(); //to correctly send the end of the connection in both sides
sock.on("close", fn) //add event listeners to destory all related sockets and clients
sock.on("close", () => { sock.destroy() }) //to destroy your side socket wrapper
Example:
const closeConn = async (sock, cb) => {
sock.ev.on("close", async ()=>{
await sock?.destroy();
if (typeof cb === "function") cb();
});
await sock?.end();
}
closeConn(sock, openSock);
You can check more here

Can't close server (nodeJS)

Why I can't close the server by requesting localhost:13777/close in browser (it continues to accept new requests), but it will gracefully close on timeout 15000? Node version is 0.10.18. I fell into this problem, trying to use code example from docs on exceptions handling by domains (it was giving me 'Not running' error every time I secondly tried to request error page) and finally came to this code.
var server
server = require("http").createServer(function(req,res){
if(req.url == "/close")
{
console.log("Closing server (no timeout)")
setTimeout(function(){
console.log("I'm the timeout")
}, 5000);
server.close(function(){
console.log("Server closed (no timeout)")
})
res.end('closed');
}
else
{
res.end('ok');
}
});
server.listen(13777,function(){console.log("Server listening")});
setTimeout(function(){
console.log("Closing server (timeout 15000)")
server.close(function(){console.log("Server closed (timeout 15000)")})
}, 15000);
The server is still waiting on requests from the client. The client is utilizing HTTP keep-alive.
I think you will find that while the existing client can make new requests (as the connection is already established), other clients won't be able to.
Nodejs doesn't implement a complex service layer on top of http.Server. By calling server.close() you are instructing the server to no longer accept any "new" connections. When a HTTP Connection:keep-alive is issued the server will keep the socket open until the client terminates or the timeout is reached. Additional clients will not be able to issue requests
The timeout can be changed using server.setTimeout() https://nodejs.org/api/http.html#http_server_settimeout_msecs_callback
Remember if a client has created a connection before the close event that connection can continually be used.
It seems that a lot of people do not like this current functionality but this issue has been open for quite a while:
https://github.com/nodejs/node/issues/2642
As the other answers point out, connections may persist indefinitely and the call to server.close() will not truly terminate the server if any such connections exist.
We can write a simple wrapper function which attaches a destroy method to a given server that terminates all connections, and closes the server (thereby ensuring that the server ends nearly immediately!)
Given code like this:
let server = http.createServer((req, res) => {
// ...
});
later(() => server.close()); // Fails to reliably close the server!
We can define destroyableServer and use the following:
let destroyableServer = server => {
// Track all connections so that we can end them if we want to destroy `server`
let sockets = new Set();
server.on('connection', socket => {
sockets.add(socket);
socket.once('close', () => sockets.delete(socket)); // Stop tracking closed sockets
});
server.destroy = () => {
for (let socket of sockets) socket.destroy();
sockets.clear();
return new Promise((rsv, rjc) => server.close(err => err ? rjc(err) : rsv()));
};
return server;
};
let server = destroyableServer(http.createServer((req, res) => {
// ...
}));
later(() => server.destroy()); // Reliably closes the server almost immediately!
Note the overhead of entering every unique socket object into a Set

Socket.io with Cluster: iterating over all open connections

I'm running Socket.io multi-threaded with the native cluster functionality provided by Node.js v0.6.0 and later (with RedisStore).
For every new change in state, the server iterates over each connection and sends a message if appropriate. Note: this isn't "broadcasting" to all connections, it's comparing server data with data the client sent on connection to decide whether to send the server data to that particular client. Consider this code sample:
io.sockets.clients().forEach(function (socket) {
socket.get('subscription', function (err, message) {
if(message.someProperty === someServerData) {
socket.emit('position', someServerData);
}
});
This worked fine when there was only one process, but now, the client receives a message for each Node process (ie. if there are 8 Node process running, all clients receive the messages 8 times).
I understand why the issue arises, but I'm not sure of a fix. How can I assign a 1-to-1 relation from one process to only on client. Perhaps something using NODE_WORKER_ID of Cluster?
This previous SO question seems somewhat related, although I'm not sure it's helpful.
This seems like a pretty common request. Surely, I must be missing something?
So if I get this straight you need to emit custom events from the server. You can do that by creating your own custom EventEmitter and triggering events on that emitter, for example:
var io = require('socket.io').listen(80);
events = require('events'),
customEventEmitter = new events.EventEmitter();
io.sockets.on('connection', function (socket) {
// here you handle what happens on the 'positionUpdate' event
// which will be triggered by the server later on
eventEmitter.on('positionUpdate', function (data) {
// here you have a function that checks if a condition between
// the socket connected and your data set as a param is met
if (condition(data,socket)) {
// send a message to each connected socket
// if the condition is met
socket.emit('the new position is...');
}
});
});
// sometime in the future the server will emit one or more positionUpdate events
customEventEmitter.emit('positionUpdate', data);
Another solution would be to have those users join the 'AWE150', so only they will receive updates for 'AWE150', like so:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
if (client_is_interested_in_AWE) { socket.join('AWE150'); }
io.sockets.in('AWE150').emit('new position here');
});
Resources:
http://spiritconsulting.com.ar/fedex/2010/11/events-with-jquery-nodejs-and-socket-io/

Categories

Resources