not able to detect mongodb shutdown - node.js

My code:
db = mongoose.connect(
config[MONGO_HOST_CONF],
config[MONGO_ACCOUNTS_DB_CONF],
config[MONGO_PORT_CONF]
}
);
db.connection.on('opening', function() {
console.log("connecting");
});
db.connection.on('open', function() {
console.log("connected");
});
db.connection.on('error', function() {
console.log("disconnected");
});
db.connection.on('close', function() {
console.log("disconnected");
});
When I start my webserver which then opens a connection to mongodb, I can see "connected" in logs.
But when I do a mongodb stop, I dont see "disconnected" in logs. Neither do I see "connecting".
I am trying to detect if for some reason mongodb went down. Then reconnect before bailing out.
What is wrong above?

opening isn't an event that is sent by Mongoose, try connecting instead.
Also, close is an event that will be called when the client is closing the connection; in the situation where the server has stopped (or crashed), it isn't sent. Try using the disconnected event for that.

Related

how to close socket if connection to server cant be established in node.js and socket.io?

currently I am using the following code in node.js with socket.io to connect to my server, which is working fine. But if my node.js server is not running, the client is trying to connect to it again and again in intervals - but I would like to stop it and close the socket on the client side if the server is not reachable. I have tried using connect_failed, but unfortunately this is never being called. how can this be done?
function findOpponent(gamemode)
{
console.log('Registering myself on nodejs Server and waiting for 2nd player');
socket = io.connect("http://gladiator.localhost:3000" , {
'query': '&uuid='+uuid+'&authkey='+auth_key+'&gamemode='+gamemode
});
socket.on('connect_failed', function() {
// --> this is never being called
console.log("Sorry, there seems to be an issue with the connection!");
});
socket.on('user join',function(msg){
alert('USER JOINED');
});
socket.on('user leave',function(msg){
console.log(msg);
alert('USER LEFT');
});
socket.on('message',function(msg){
alert(msg);
});
socket.on('gamestart',function(data){
console.log('gamestart');
alert(data.msg);
});
}
try autoConnect and reconnection options for socket io client
{ autoConnect: false, reconnection: false}
EDIT:
and you can listen on connect_error event for catch connection error
socket.on("connect_error", callback)

socket.io client can't connect/reconnect reliably

I am utilizing socket.io V3.1.1 and am trying to figure out how to get the client to reconnect after the connection is disconnected due to a phone going asleep. When I run the code, it connects, refreshes an order, and then I press the power button on the iPhone to cause it to sleep. I then press the home key, and I see a disconnect event, followed by a connect event which refreshes the order. If I repeat the process, I see it disconnect, but I never see a connect event.
The question is, how does one reliably connect/reconnect and/or why don't I get additional connect events?
Here's a sample console.log output:
connect
refreshOrder 1234
disconnect due to transport error
connect
refreshOrder 1234
disconnect due to transport error
and then no more events
Here's the primary code that's involved:
const socket = io("wss://xyz.org:3000");
socket.on('connect', () => {
console.log("connect");
if (order_id !== null){
refreshOrder(order_id);
}
});
socket.on("disconnect", (reason) => {
console.log("disconnect due to " + reason);
socket.connect();
});
I also have the following event handlers, but they never get called:
socket.on('reconnect', () => {
console.log('reconnect');
if (order_id !== null){
refreshOrder(order_id);
}
});
socket.on("connect_error", (err) => {
console.log("connect_error: " + err);
setTimeout(() => {
console.log("socket.connect retry");
socket.connect();
}, 1000);
});
The answer is that you should ignore the disconnect and let the built-in reconnect code handle it. I believe that my problem was that I had looked at examples of pre-V3 code and didn't understand that it was handled differently in V3. So, a better disconnect event handler would be
socket.on("disconnect", (reason) => {
console_log("disconnect due to " + reason);
if (reason === "io server disconnect") {
// disconnect initiated by server. Manually reconnect
socket.connect();
}
});

Prevent Socket connection from initializing again

I am trying to make a chat app which sends first message as "Hi. there".
But due to some some reasons (unstable internet connection might be one) the socket get initialized multiple times and sends the "Hi. there" message multiple times. Below is the code. How to stop the app for sending multiple messages?
io.socket.on('connect', function() {
/* On successfull connection to server */
console.log('Connected to server');
//Some code here
io.socket.get(url + '/userstatus/subscribe', function(resData, jwres) {
//Some code here
io.socket.on("userstatus", function(event) {
//Socket updartes
// Send Message code at this line.
}
}
});
You need to change your client side code, so that it stores state, and sends it to the server on reconnect. That way the server can give the correct response.
Something like this might work:
socket.on('connect', function() {
/* On successfull connection to server */
console.log('Connected to server');
socket.emit('state', state_object);
});

How do I detect client disconnected inside a net.CreateServer?

Good day,
I was playing with the example found here on SO: PHP Socket Server vs node.js: Web Chat.
Using gMUD (a telnet-like client) to connect to my server, I can't seem to be able to detect when the client disconnect from the server.
Here is the two events I'm using:
socket.on('end', function() {
console.log('end');
});
socket.on('error', function() {
console.log('error');
});
To be honest, I thought the error event could do it. Is there any other events I'm actually missing?
I found it. It was abvious:
socket.on('close', function() {
//Do something
});

Node.js and Socket.IO - How to reconnect as soon as disconnect happens

I'm building a small prototype with node.js and socket.io. Everything is working well, the only issue I'm facing is that my node.js connection will disconnect and I'm forced to refresh the page in order to get the connection up and running again.
Is there a way to reestablish the connection as soon as the disconnect event is fired?
From what I've heard, this is a common issue. So, I'm looking for a best-practice approach to solving this problem :)
Thanks very much,
Dan
EDIT: socket.io now has built-in reconnection support. Use that.
e.g. (these are the defaults):
io.connect('http://localhost', {
'reconnection': true,
'reconnectionDelay': 500,
'reconnectionAttempts': 10
});
This is what I did:
socket.on('disconnect', function () {
console.log('reconnecting...')
socket.connect()
})
socket.on('connect_failed', function () {
console.log('connection failed. reconnecting...')
socket.connect()
})
It seems to work pretty well, though I've only tested it on the websocket transport.
edit: Socket.io has builtin-support now
When I used socket.io the disconnect did not happen(only when i closed the server manually). But you could just reconnect after say for example 10 seconds on failure or something on disconnect event.
socket.on('disconnect', function(){
// reconnect
});
I came up with the following implementation:
client-side javascript
var connected = false;
const RETRY_INTERVAL = 10000;
var timeout;
socket.on('connect', function() {
connected = true;
clearTimeout(timeout);
socket.send({'subscribe': 'schaftenaar'});
content.html("<b>Connected to server.</b>");
});
socket.on('disconnect', function() {
connected = false;
console.log('disconnected');
content.html("<b>Disconnected! Trying to automatically to reconnect in " +
RETRY_INTERVAL/1000 + " seconds.</b>");
retryConnectOnFailure(RETRY_INTERVAL);
});
var retryConnectOnFailure = function(retryInMilliseconds) {
setTimeout(function() {
if (!connected) {
$.get('/ping', function(data) {
connected = true;
window.location.href = unescape(window.location.pathname);
});
retryConnectOnFailure(retryInMilliseconds);
}
}, retryInMilliseconds);
}
// start connection
socket.connect();
retryConnectOnFailure(RETRY_INTERVAL);
serverside(node.js):
// express route to ping server.
app.get('/ping', function(req, res) {
res.send('pong');
});
Start reconnecting even if the first attempt fails
If the first connection attempt fails, socket.io 0.9.16 doesn't try to reconnect for some reason. This is how I worked around that.
//if this fails, socket.io gives up
var socket = io.connect();
//tell socket.io to never give up :)
socket.on('error', function(){
socket.socket.reconnect();
});
I know this has an accepted answer, but I searched forever to find what I was looking for and thought this may help out others.
If you want to let your client attempt to reconnect for infinity (I needed this for a project where few clients would be connected, but I needed them to always reconnect if I took the server down).
var max_socket_reconnects = 6;
var socket = io.connect('http://foo.bar',{
'max reconnection attempts' : max_socket_reconnects
});
socket.on("reconnecting", function(delay, attempt) {
if (attempt === max_socket_reconnects) {
setTimeout(function(){ socket.socket.reconnect(); }, 5000);
return console.log("Failed to reconnect. Lets try that again in 5 seconds.");
}
});

Resources