I am using node.js and socket.io to create a chat application.
socket.on('disconnect',function(data){
console.log("disconnected");
}
This event is fired as soon as the client gets disconnected(tab closed or network problem).
I want the disconnect event to be fired after 1 minute of disconnection from client. Is that possible? Is there any configuration in socket.io?
That capability is not built into socket.io. The disconnect event fires when the socket is disconnected. Period. If you want to trigger some activity 1 minute after a disconnect, you can build your own timer to do so.
socket.on('disconnect',function(data){
setTimeout(function() {
console.log("disconnected");
}, 60 * 1000);
}
If you want to trigger your event only if the client does not reconnect within 1 minute, then you can code that also, but it is a little more involved as you have to save the timer for the setTimeout() and then cancel it if that specific client reconnects before the timer fires.
Based on what you put in your answer, here's what I think is an improved version:
(function() {
var origClose = socket.onclose;
socket.onclose = function(reason){
var self = this;
var args = Array.prototype.slice.call(arguments);
/* Delay of 1 second to remove from all rooms and disconnect the id */
setTimeout(function() {
origClose.apply(self, args);
}, 60 * 1000);
}
})();
You have some parameters to control this behavior server-side. See close timeout and heartbeat timeout here
and if you're using v1.0 you'll need to set the options in the new style described here.
Note that these don't technically do what you're asking - they simply lengthen the amount of time a client has to reconnect.
Socket.onclose is fired immediately after disconnection before the disconnect event.
disconnect event can be delayed by changing as follows.
socket.onclose = function(reason){
console.log(socket.adapter.sids[socket.id]);
Object.getPrototypeOf(this).onclose.call(this,reason);
/* Delay of 1 seconds to remove from all rooms and disconnect the id */
setTimeout(function() {
if (!this.connected) return this;
debug('closing socket - reason %s', reason);
this.leaveAll();
this.nsp.remove(this);
this.client.remove(this);
this.connected = false;
this.disconnected = true;
delete this.nsp.connected[this.id];
this.emit('disconnect', reason);
}, 60 * 1000);
}
Related
Right part of my code is
io.sockets.on('connection', function(socket){
var interval = setInterval(function() {
repaintGraph()
socket.emit('set data chart', '{"series":[['+series+']]}');
}, 1000 );
The chart in this case, if I have 3 users connected, the chart updates 3 times in one second I need to execute the code 1 time in 1 second, regardless of the number of clients
You can run the interval code outside of the connection code:
setInterval(function() {
repaintGraph();
io.emit('set data chart', '{"series":[['+series+']]}');
}, 1000);
io.on('connection', function() {
...
});
io.emit() will broadcast the message to all connected clients, every second.
There's a little bit of an inefficiency in the code, in that it will call repaintGraph() every second even if there aren't any clients connected, but it makes the code much easier.
try to use
socket.broadcast.emit('event',data)
I am wondering how I can send out a message to sockets on an interval, currently I am doing:
io.on('connection', function(socket){
setInterval(function () {
socket.emit('message', variable);
}, 100);
...
Each user then has an interval emitting messages every 100ms. Is there a better way of doing this?
I am also confused about how emit works: I was under the impression it sent the message to all sockets, but if I only start this interval for the first socket that connects and not the following sockets only the first socket receives the message?
Use io.emit to emit to all connected sockets. You can still do this in an interval as well.
// Only needed if you have to do something with a specific socket
io.on('connection', handleSocket);
setInterval(() => {
io.emit('message', variable);
}, 100);
just don`t forget to call clearInterval() finction when the socket connection is close.
I have two .js file. One emits the event and another listens for it. The code looks as below.
Emitter
var EventEmitter = require('events').EventEmitter;
utils.inherits(ConfigFileManager, EventEmitter);
var manager = new ConfigFileManager();
var watcher = chokidar.watch(CONFIG_DIR, {persistent: true});
watcher.on('add', function (path) {
manager.emit('monitor', 'print this data');
});
watcher.on('change', function (path) {
console.log('change event fired');
manager.emit('monitor', 'print this data');
});
module.exports = manager;
The chokidar.watch keeps the event queue and restricts node from exiting. Now, listener is in different file, as given below.
Listener
var manager = require('./emitter');
manager.on('monitor', function(data) {
console.log(data);
});
and I run "node listener.js". The first time "add" event calls the listener, and all is fine. However when I change a file, the event is emitted, but the listener never gets it. If I add a setTimeout at the end of the listener.js, the listener is getting events until the timeout expires. So, once the listener script completes, the events are not received. How can I make the listener to listen forever?
Also, if I keep the listener code also in emitter.js, then it works, because chokidar.watch keeps the script from terminating. But, I want to keep them separate for better organization.
I have a socket.io server and a client runing correctly. Each time that the server is down, the client try to connect again each 5 seconds. When the server is up again they connect without problems.
But the problem comes when I wait long time before up the server again, when the server is up, it crashes showing :
info - socket.io started
debug - client authorized
info - handshake authorized DqN4t2YVP7NiqQi8zer9
debug - setting request GET /socket.io/1/websocket/DqN4t2YVP7NiqQi8zer9
debug - set heartbeat interval for client DqN4t2YVP7NiqQi8zer9
debug - client authorized for
debug - websocket writing 1::
buffer.js:287
pool = new SlowBuffer(Buffer.poolSize);
^
RangeError: Maximum call stack size exceeded
Client reconnection (Executed each 5 seconds while is not connected):
function socket_connect() {
if (!socket) {
socket = io.connect('http://192.168.1.25:8088', { 'reconnect':false, 'connect timeout': 5000 });
} else {
socket.socket.connect();
}
socket.on("connect", function () {
clearInterval(connect_interval);
connect_interval = 0;
socket.emit('player', { refresh_data:true });
});
}
On server side, only with the socket instance, it crashes:
var io = require('socket.io').listen(8088);
I think that the problem is:
When the server goes up, it recive all the connections emited by the client each 5 seconds, (15 hours disconnected * 60 m * 60 s / 5 seconds reconnection) and it crashes.
What can i do to close the connections that the server try to do?
PS:If i reload the client, and after up the server, it works
The main idea for socket.io.js is to reuse an existing connection.
You should only connect it once and then exchange messages by using socket.emit()
I am not sure why you are creating a new connection between your client and server for every 5 seconds. There is a limit on the number of connections the server can create, but that should be more than enough. If you put it in a loop then eventually the server will run out of sockets.
io.connect has to be executed once on the client, then may be you can socket.emit() every 5 seconds. Remove the { 'reconnect':false, 'connect timeout': 5000 } and you will be fine.
I founded the problem...
Each time that the function socket_connect() is called, a "socket.on("connect" ..." function is created. So when the server turns up, a new connection is created, but the event "socket.on("connect" is fired multiple times...
The solution was:
function socket_connect() {
if (!socket) {
socket = io.connect('http://192.168.1.25:8088', { 'reconnect':false, 'connect timeout': 5000 });
} else {
socket.socket.connect();
}
}
socket.on("connect", function () {
clearInterval(connect_interval);
connect_interval = 0;
socket.emit('player', { refresh_data:true });
});
I know socket.io has a built in feature for reconnecting and everything, however I don't think that it is working - as I have seen from others it's also not working for them either.
If a user puts their computer to sleep, it disconnects them, and then when they open it back up they are no longer connected so they don't any of the notifications or anything until they refresh the page. Perhaps it's just something that I'm not doing correctly?
var io = require('socket.io').listen(8080);
var users = {};
////////////////USER CONNECTED/////
console.log("Sever is now running");
io.sockets.on('connection', function (socket) {
//Tell the client that they are connected
socket.emit('connected');
//Once the users session is recieved
socket.on('session', function (session) {
//Add users to users variable
users[socket.id] = {userID:session, socketID:socket};
//When user disconnects
socket.on('disconnect', function () {
//socket.socket.connect();
var count= 0;
for(var key in users){
if(users[key].userID==session)++count;
if(count== 2) break;
}
if(count== 1){
socket.broadcast.emit('disconnect', { data : session});
}
//Remove users session id from users variable
delete users[socket.id];
});
socket.on('error', function (err) {
//socket.socket.connect();
});
socket.emit("connection") needs to be called when the user reconnects, or at least the events that happen in that event need to be called.
Also socket.socket.connect(); doesn't work, it returns with an error and it shuts the socket server down with an error of "connect doesn't exist".
The problem is related to io.connect params.
Look at this client code (it will try to reconnect forever, with max delay between attempts 3sec):
ioParams = {'reconnection limit': 3000, 'max reconnection attempts': Number.MAX_VALUE, 'connect timeout':7000}
socketAddress = null
socket = io.connect(socketAddress, ioParams)
There are two important parameters out there, related to your problem:
reconnection limit - limit the upper time of delay between reconnect attemts. Normally it's getting bigger and bigger in time of server outage
max reconnection attempts - how many times you want to try. Default is 10. In most cases this is the problem why the client stops trying.