Socket.io handle Client internet off event - node.js

Socket.io how to handle client internet disconnect event?
I read heartbeat on stackoverflow but that solution does not work for me.
I found a ping solution but I think it is a bad approach to ping all the connected user, it will slow down the server
here is my code, kindly guide how to handle internet disconnect event?
io.on('connection', function(client) {
client.on('online', function(data) {
socket_api.user_online(data.user_id, function (err,res){
if (err) {
client.emit ('error',err);
} else {
console.log ("client connected")
client.emit ('online_response', res);
}
});
// client.emit('messages', 'Hello from server');
});
client.on('disconnect', function (data){
console.log ("Client disconnected");
});
});

// use this on server side
function sendHeartbeat(){
setTimeout(sendHeartbeat, 8000);
io.sockets.emit('ping', { beat : 1 });
}
io.sockets.on('connection', function (socket) {
socket.on('pong', function(data){
console.log("Pong received from client");
});
}
setTimeout(sendHeartbeat, 8000);
.................................................
// on Client side
socket.on('ping', function(data){
socket.emit('pong', {beat: 1});
});
hope this help you

Related

sokect client data handling in node patterns

So i'm building an vscode extension in typescript and node and i have a python app which sends data with socket to localhost 8080 and im catching it like this :
export default async function getSock(port, adress, dataOld): Promise<void> {
let server = net.createServer(function (socket) {
socket.setEncoding('binary');
socket.on('data', async function (data) {
console.log('client send:' + data);
let m = port
new **UI**(data);
server.close()
});
socket.on('error', function (exception) {
console.log('socket error:' + exception);
socket.end();
});
socket.on('close', function (data) {
console.log('client close:' + data);
});
socket.on('end', function() {
console.log('disconnected from server');
server.close()
});
})
server.listen({port: port, adress: adress});
}
Now i need some mechanism that if listening for 5 seconds and no data passed from the socket, i stop listening and call "new UI(dataOld)"

Connection socket.io incremented after stopping the server

I have a problem with socket.io from nodeJs.
I am trying to create a connection from a client to a server. Once the client is connected, the server sends a message to the client (ack).
Until then, everything works fine but when I disconnect the server and restart it, it sends me the message twice to the client.
If I repeat the manipulation a third time, three messages will appear.
I have captured the problem:
client.js
var socket = require('socket.io-client')('http://localhost:8050', {
'forceNew':true
});
socket.on('connect', onConnect);
function onConnect(){
console.log('connect ' + socket.id);
socket.emit('sendConnect','First connect');
socket.on("ack", function(data) {
console.log("ack reçu");
});
socket.on('disconnect', function(reason) {
console.log(reason);
});
}
server.js
var io = require("socket.io");
var sockets = io.listen(8050);
sockets.on('connection', function (socket) {
socket.on('sendConnect', function (data) {
console.log("message :" + data);
socket.emit('ack');
socket.on('disconnect', function() {
console.log('Got disconnect!');
});
});
});
I looked if this bug was already arriving without finding an answer.
I must surely be doing something wrong!
Thank you in advance for your help.
Your onConnect function adds new event listeners each time the socket connects. Move the event subscriptions out of onConnect like this:
var socket = require('socket.io-client')('http://localhost:8050', {
forceNew: true
});
socket.on('connect', onConnect);
socket.on('ack', function(data) {
console.log('ack reçu');
});
socket.on('disconnect', function(reason) {
console.log(reason);
});
function onConnect() {
console.log('connect ' + socket.id);
socket.emit('sendConnect', 'First connect');
}

Wait/reconnect until TCP client connection can be established?

Here is an example of how to create a TCP client connection from the node net docs (https://nodejs.org/api/net.html#net_net_connect_options_connectlistener)
const client = net.createConnection({ port: 1905 }, () => {
// 'connect' listener
console.log('connected to server!');
client.write('world!\r\n');
});
client.on('data', (data) => {
console.log(data.toString());
client.end();
});
client.on('end', () => {
console.log('disconnected from server');
});
If the server is not available I get Error: connect ECONNREFUSED 127.0.0.1:1905.
What would be a good way to wait/reconnect until the server is available and connect when it is, instead of throwing an error?
EDIT: Here is an alternative approach I have tried, but here I get the problem
MaxListenersExceededWarning: Possible EventEmitter memory leak
detected. 11 connect listeners added. Use emitter.setMaxListeners() to
increase limit
I would like the latest listener to replace earlier listeners. They all listen for the same thing. I just want to retry.
function initTcpClient() {
console.log("Initiating TCP client...")
var tcpSocket = new net.Socket();
const client = net.createConnection({ port: 1905 }, () => {
tcpSocket.on('error', function onError(err) {
setTimeout(connect, 1000);
});
connect();
function connect() {
console.log("Looking for TCP server...");
tcpSocket.connect(argv.tcpport, argv.tcphost, function onConnected() {
console.log("Connecting to TCP server...");
tcpSocket.on('data', function onIncoming(data) {
if (connectedWebsocketClient) {
console.log('Forwarding to WebSocket: %s', data);
webSocketClient.send(data.toString());
} else {
console.log('Not connected to websocket client. Dropping incoming TCP message: %s', data);
}
});
tcpSocket.on('close', function onClose(hadError) {
console.log("Connection to TCP server was closed.");
connectedToTcpServer = false;
setTimeout(connect, 1000);
});
console.log("Connected to TCP server.");
connectedToTcpServer = true;
});
}
}
Here to elaborate on my comment. Is an example that will work. Try it with a simple tcp server. Start the client and then after a few seconds start the server. It is important to register you listeners after a reconnect happens in onError You may also want to have a limit of how many times you want to try to reconnect.
const net = require('net')
let client = connect()
client.on('data', onData);
client.on('error', onError);
client.on("close", onClose);
function onData(data) {
console.log(data)
}
function onError(err) {
if(err.message.indexOf('ECONNREFUSED') > -1) {
//do recconect
console.log("Attempting to reconnect shortly")
setTimeout(()=>{
client = connect();
client.on('data', onData);
client.on('error', onError);
client.on("close", onClose);
},1000)
}
}
function onClose() {
console.log("Removng all listeners")
client.removeAllListeners("data");
client.removeAllListeners("error")
}
function connect() {
const c = net.createConnection({
port: 3000
},
()=>{
console.log('connected')
});
return c
}

Garbage socket client nodejs?

I'm a new in nodejs, i have project about TCP server client , I init 2000 client and send to server 1KB/1s on terminal, after i click X button on terminal (disconnect client unusual).
On my server, only 1500-1600 client disconnect, the rest client still not disconnect ??
So how can i clean this garbage connection ??
How can i check status of socket ??
Client code :
var test = setInterval(function () {
var client = socks.connect(function (socket) {
lstClient.push(socket);
var message = '';
console.log('>> Connection successful');
socket.on('data', function (data) {
console.log(data.length);
});
var myTimer = setInterval(function () {
if (socket.writable) socket.write(datareal.toString());
else clearInterval(myTimer);
}, 5000);
socket.on('error', function (err) {
console.log(err);
});
socket.on('close', function () {
console.log('Disconnect socket...');
socket.destroy();
});
})
}, 15);
Thanks to advance !!

Socket.io send data only a client who make request

I'm sending data to all clients but I need to send the data only one client (who make request) too.
app.post(.....){
myModel.save(function (err) {
if (err) return handleError(err);
///send to all
io.sockets.emit("ev", { ...... });
//// send to one client
......
});
}
There is a function called io.sockets.emit but there is no io.socket.emit.
I assume that in the post method you have identified the user or session.
So you can create a room per user to later emit on it.
client.js
var room = "#usernameRoom";
socket.on('connect', function() {
socket.emit('privateroom', room);
});
socket.on('privatemessage', function(data) {
console.log('Incoming private message:', data);
});
server.js
io.sockets.on('connection', function(socket) {
var socket_room;
socket.on('privateroom', function(room) {
socket_room = room;
socket.join(room);
});
socket.on('disconnect', function() {
if (socket_room) {
socket.leave(socket_room);
}
});
});
app.post(.....){
myModel.save(function (err) {
if (err) return handleError(err);
///send to all
io.sockets.emit("ev", { ...... });
//// send to one client
// now, it's easy to send a message to just the clients in a given private room
privateRoom = "#usernameRoom";
io.sockets.in(privateRoom ).emit('privatemessage', 'Never reveal your identity!');
});
}
hope that helps

Resources