Node.js - Socket.IO 1.0 - Timeout event - javascript

I'm using Socket.IO (the latest version 1.1.0) to exchange messages with an Android app (the client).
I would like to set a timeout (5s for example) to check if my client is still connected or not (I would like to handle the case when the Android app crashes). Moreover, I would like to generate an event when a this timeout occurs.
What I want to do looks like this:
1/ Set the timeout
var socket = require('socket.io')({
//options go here
'timeout': 5000 //set the timeout to 5s
});
2/ Handle timeout event:
socket.on('timeout', function(){
//my treatment
});
But I don't find any implementation to handle the timeout.
Thanks for your help !

That's not what the timeout setting handles. The timeout is how long the server will wait for a re-connect before it tears down that connection. You probably don't want to set it that short; possibly even leave it at the default.
Socketio automatically sends heartbeats by default. You really should just need to assign a function to run when the 'disconnect' message is received on the server side.
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
Check out this post for more information about the heartbeat:
Advantage/disadvantage of using socketio heartbeats

Related

Socket IO keeps disconnecting and reconnecting

I'm very very new to sockets and socket.io, so I apologize if this is an obvious question. I'm using the C# client for Socket.IO and have a local javascript server running. Here is my app.js:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket) {
console.log('A user connected');
socket.on('test', function () {
console.log('Test run'); });
socket.on('disconnect', function () {
console.log('A user disconnected'); });
});
http.listen(3000, function() {
console.log('listening on localhost:3000'); });
In my main C# class (it is a Windows Forms application) the only line of code I have relating to the sockets at all is the instance variable private Socket socket = IO.Socket("http://localhost:3000/");. Yet for some reason, the server repeatedly receives the connect and disconnect events. Here is a screenshot of my console:
screenshot
This all happens automatically, as soon as I run my C# program, without any interaction, and stops as soon as I close it. Any ideas as to why it keeps connecting/disconnecting?
EDIT: For whatever reason the problem seems to go away when I remove Newtonsoft.json from the project. However, without it I cannot use the Emit function as well as others. Is there a workaround to this?
To anyone encountering this issue, check if client & server speak the same protocol version.
On a high-level, this is likely to be caused by protocol version mismatch between server and client. I've had the same issue in JS app. Turned out I was using some older version of socket.io on the client and the latest on the server. In the repository you provided we can find:
// EngineIoClientDotNet/Src/EngineIoClientDotNet.mono/Parser/Parser.cs
public static readonly int Protocol = 3;
So this (now deprecated) client is using Engine.IO protocol v3. You didn't provide info which socket.io version you were using on the server, but it simply might've been using different revision on Engine.IO protocol.
As a side note, speaking more low-level: I guess that the client might be able to connect, but it does not respond to server's first ping command in a proper way (or the other way around). Therefore the connection is immediately dropped. Socket.IO has a history of breaking changes in how ping-pong mechanism is implemented, and this might be the underlying root cause.

detect socket.io disconnect and destroy events client side

I have html page sent by node.js server and socket.io component that connects to that server like this:
var socket = io();
Also several socket events:
socket.on('server-message', function(type, content) {
...
});
socket.on('server-update', function(type, content) {
...
});
The problem is that in the moment server is stopped, i get client side errors:
https://example.com/socket.io/?EIO=3&transport=polling&t=LptmQyC net::ERR_CONNECTION_REFUSED
Once server is started again it crashes in a 30 seconds after.
It looks like i could use a detection if server is not available anymore and just destroy all socket related events, then reconnect by page refresh or some button.
Maybe someone could help me with this.
I dont believe that much can be done about the error, its internal socket.io error that is a result of unsuccessful server polling.
For better understanding, once connection is severed, socket.io goes into ajax polling and will try to reconnect as soon as possible (meaning as soon as server is up again).
Server crash after reconnect on the other hand can be addressed very easy. The code you presented is only functional in terms of how to connect, you are missing handlers for disconnect and optionally - reconnect.
I will show you how you can add to this code to manage disconnects (and prevent server crashes after bringing it back up).
First of all connect to server:
var socket = io();
Create a disconnect event right after (btw its also a code for server side disconnect event):
socket.on('disconnect', function() {
destroy_socket_events();
});
Create function that will destroy all your listeners:
var destroy_socket_events = function() {
socket.off('disconnect');
socket.off('server-message');
socket.off('server-update');
// add all other socket events that you have in here ...
};
Now what is going to happen is this:
connection is made
server is stopped
client triggers disconnect event
function destroys all of your socket listeners
server is back up
client reconnects (socket.io will do it because of the polling)
no listener is ever triggered at that point
So you can safely reinitialize all of your code and attach listeners again properly.

Jetty Web Socket Timeout

I am trying to establish a Web Socket Connection using Jetty 9.3.0 RC.
function checkDetails(port) {
var ws = new WebSocket("ws://localhost:9995/application");
ws.onopen = function(event) {
console.log("onopen called...");
}
ws.onerror = function(event){
console.log('onerror called...');
}
ws.onmessage = function(event) {
console.log("onmessage called..." + event.data);
}
ws.onclose = function(event) {
console.log("onclose called..." + port);
console.log(event);
ws.close();
}
}
The code works fine if the port 9995 used for creating the Web Socket connection is not occupied by some other process.
var ws = new WebSocket("ws://localhost:9995/application");
But in case if the port is occupied by some other process, then it keeps on trying to connect with that port until the port is released.
I need to provide a timeout so that if the port does not respond in 3 mins then the Web Socket should release (or stop listening) the port and display a console log.
Please let me know the simplest way to achieve this.
From client side you are connecting to some web socket. If port (9995 in your case) is available to connect to then it means that some program (in server mode) is listening and responding. And does something - answers with some data. So, you can connect to such program if it exists and answers or you cannot if there is no server listener for port 9995. When you say "port is occupied" by some other process that means that this process exist and answers. And this process will respond with whatever it is designed for. So, from client side, all what you do is connect to existing and running process which listens for this port in the server mode. That's it and that's all.
However, if we ignore your comment that OP is only about client side then my first suggestion would be to look on the server configuration and check that it is in multithread mode and can answer and proceed multiple requests at once. What you are describing looks like you have singe thread process which works with only one request and can answer next one when current is finished. That sounds like "process occupied". But since comment insist that we are talking only about client side then this speculation would be unnecessary.

Socket.IO ping without client-side script

I have an Android application and when somebody forces it to stop it doesn't fire the disconnect event on the server side.
Since I can't force people to update their android app, I can't make a ping event handler on the client side.
How could I check on the server side whether the client is active without client-side modification?
You need to find out why the disconnect event doesn't fire.
Have you put the socket's disconnect event inside the connection callback?
Also pay attention to variable io and socket. Maybe you put it wrong.
io.on('connection', function (socket) {
console.log('user connected');
socket.on('disconnect', function () {
console.log('user disconnected');
});
});
If the structure is already right, then I believe you should check the client's code.

Websocket availability using socketio

I'm trying to detect whether the websocket is running before allowing clients to connect to it. Consider the following code:
var socket = io.connect('1.1.1.1:1234');
socket.on('connect',function() {
console.log('Client has connected to the server');
});
socket.on('disconnect',function() {
console.log("The client has disconnected from the server");
});
How can I make sure that this block is only called if the server on that IP is actually running and how can I output a message to the users stating that the server is not up?
Thank you
You would need to fire the io.connect() atleast once (consider this as a ping) to detect if server is up, but you can then handle the failure to connect with the socket.on('connect_failed', function () {}) event handler and show a message to user that the 'server is down'. Have a look at Exposed Events for the client
Further, if you would want to reduce the number of times the reconnect is attempted, you can change the socket.io configuration setting for 'reconnect' to false. Checkout Socket.io Configuration for more details

Categories