How Do I not call socket.disconnect() when in queue - socket.io

When the wifi get disconnected for 10 seconds and gets reconnect, it calls the disconnect then
"connect" at the same time (instantaneously). I was wondering how I can make the 'disconnect' not be called when the wifi disconnects then reconnects quicky.
The disconnect should only be called when the wifi is disconnected for a long time or the user force quits
io.on('connection', (socket: any) => {
console.log(new Date(), 'Socket connected', socket.id);
})
socket.on('disconnect', () => {
console.log('DISCONNECT');})

Related

Socket.io : Do I need to disconnect the client after every new message in a socket.io chat app?

I am new to web-sockets. I was reading this article on medium and in a part of the client code, the code disconnects the socket every time a new message is emitted.
Why is it so? Does this have some design advantage, is this how it is done?
Why not leave the socket connected for more message streams?
-----EDIT------
Here is the code that I am talking about. The code is from this blog
newMessageReceived() {
const observable = new Observable<{ user: String, message: String}>(observer => {
this.socket.on('new message', (data) => {
observer.next(data);
});
return () => {
// Why is the coder disconnecting the socket here?
this.socket.disconnect();
};
});
return observable;
}

Socket.io don't emit after disconnect event

I want to send data from the server to the client after a disconnect socket.io event occurs.
Server :
const clients = {};
io.on('connection', socket => {
clients[socket.id] = socket;
console.log('connect : ' + socket.id);
socket.emit('socket-connect', 'connected');
socket.on('disconnect', () => {
socket.emit('socket-disconnect', 'disconnected');
delete clients[socket.id];
console.log('disconnect : ' + socket.id);
});
});
Client :
const socket = openSocket('localhost');
socket.on('socket-connect', data => {
console.log(data);
});
socket.on('socket-disconnect', data => {
console.log(data);
});
If socket connected, the server send a connect message to client and it works, but it does not send interrupted messages to the client if the disconnection occurs.
console.log('disconnect : ' + socket.id); on server showing disconnect with the socket.id.
I'm using socket.io v2.0.4 both on server and client.
How can I send data from the server if a socket disconnect event occurs?
Event: disconnect is fired upon disconnection. This simply means, for some reason, there is no connection between the client and the server.
So in this situation, you cannot send data to the client as the client is not connected. Disconnection may happen if the client's network is not available(read Internet failure) or the client environment(ex: browser) crashed or the user closed the tab.

Socket.emit() outside socket.on()

Do we always have to use socket.emit() inside a socket.on() like that:
io.sockets.on('connection', function (socket) {
console.log('User connected !');
retrieveDictionnary((dictionnary) =>{
socket.emit('dictionnarySend', dictionnary);
}
}
I want to create on my client side a function which ask information to the server when I click on a button:
translateServer(parameter, control){
this.socket.emit('translate', [parameter,control]);
}
But it seems that it's not working, the server never receive this message.
Thank you !
The pattern you are using above is the recommended way of interacting with a socket (ie acquiring a socket instance when the 'connection' event fires, and then calling emit() from that socket instance, etc).
If I understand your client-side requirements correctly, you are wanting to send data to the server via web sockets - are you sure the socket that you have established a web socket connection between the client and server?
For instance, if you add the following to your client-side code, you should see a success message in your console:
const socket = io.connect('YOUR SERVER ADDRESS');
socket.on('connect', () => {
console.log('connected to server!');
// [UPDATE]
// This assumes you have a <button> element on your page. When
// clicked, a message will be sent to the server via sockets
document.querySelector('button').addEventListener('click', (event) => {
// Prevent button click reloading page
event.preventDefault();
// Send message to server via socket
socket.emit('MESSAGE_ID', 'test message from client' + new Date());
});
});
Update
This shows your original server code, expanded with the detail needed to receive and print data sent from client via sockets:
io.sockets.on('connection', function (socket) {
console.log('User connected !');
// Register a server handler for any messages from client on MESSAGE_ID channel
socket.on('MESSAGE_ID', (message) => {
// Print the message received from client in console
console.log('message from client', message);
})
retrieveDictionnary((dictionnary) =>{
socket.emit('dictionnarySend', dictionnary);
}
}

Switch socket server on disconnect

I am trying to connect a new server when the first server is down and attempted in reconnect_failed. Upto now it is working fine, first server disconnects, second server connected and listening the message.
socket.on('reconnect_failed', function () {
console.log("reconnect_failed");
socket = io.connect('http://localhost:4000',{
'reconnectionDelay': 100,
'reconnect':false,
'reconnectionAttempts': max_reconnects});
console.log(socket);
});
socket.on('new message', function(msg){
console.log(msg);
document.getElementById("chat").innerHTML = msg;
});
But at the client side "new message" event is not listened by second server. Due to that socket is initiated inside reconnect failed. Is there any other way to process with less code.
What I would do is have a function to switch server on disconnection.
Something like :
function initSocket(i){
sockets = io.connect(servers[i], {
'reconnectionDelay': 100,
'reconnect':false,
'reconnectionAttempts': max_reconnects});
sockets.on("connection", function(socket){
socket.on('connect',function(data){});
socket.on('new message', function(msg){
console.log(msg);
document.getElementById("chat").innerHTML = msg;
});
socket.on('reconnect_failed', function () {
console.log("reconnect_failed");
i==0 ? 1 : 0; //switch the value of i
initSocket(i) //init a socket on the other server
});
});
}
var servers = ["http://localhost:3000","http://localhost:4000"];
initSocket(0); //start with server 0 (http://localhost:3000)
This should give you the switch between your 2 servers on disconnect, with the exact same properties and event listeners. When one crashes, the other takes over.

Socket.io client only joins room on every other connection

I've been trying to make a basic notification system that uses rooms in Socket.io. However, for some reason, it only works every other time you refresh the page.
I've simplified the code to make it easier to debug, but the issue remains. Each time I refresh the page, everything seems to work except joining a room (which only works half the time). What could be going on?
edit: I'm using Socket.io version 1.1.0 and Node.js version 0.10.31
edit2: Added FunnyLookinHat's suggestion (but it still doesn't solve the problem)
Client-Side Code:
socket = io.connect('example.com:8081'),
socket.on('connect', function () {
socket.on('startup', function(data) {
console.log(data.message);
});
socket.emit('joinRoom');
});
Server-Side Code:
var io = require('socket.io').listen(8081);
io.sockets.on('connection', function (socket) {
console.log(socket.id + ' connected!');
socket.emit('startup', { message: 'Socket started!' });
socket.on('joinRoom', function(){
console.log(socket.id + ' joining room lobby'); // prints on every other request
socket.join('lobby');
});
socket.on('disconnect', function() {
console.log(socket.id + ' disconnected!');
});
});
Client Console:
Socket started!
(refreshed page)
Socket started!
Server Console:
UIBqVuOiF1fegMIMAAAB connected!
UIBqVuOiF1fegMIMAAAB joining room lobby
UIBqVuOiF1fegMIMAAAB disconnected!
(refreshed page)
x3nMilBOjjFVjBFJAAAC connected!
(after about a minute once the client window has been closed or refreshed)
x3nMilBOjjFVjBFJAAAC disconnected!
Race condition! Try doing the following in your client code:
socket = io.connect('example.com:8081'),
socket.on('connect', function () {
socket.on('startup', function(data) {
console.log(data.message);
});
socket.emit('joinRoom');
});

Resources