Reputation: 45
i am use ws package of npm in my node.js project for socket programming
here is my code....
var server = require('ws').Server;
var serverConnection = new server({port : 5000});
serverConnection.on('connection',function(ws){
console.log('websocket is created on at ws://{{IP_ADDRESS}}:5000');
ws.on('message',function(requestedString){
var iCounter = 0;
function doSetTimeout() {
if(ws.readyState == 1)
{
iCounter = iCounter + 1;
socketData = {'index' : iCounter}
ws.send(JSON.stringify(socketData),function ack(error){
if(error){
console.log("Occure error in socket");
console.log("error : "+error);
}
});
}
if(ws.readyState == 1)
{
setTimeout(function() {
doSetTimeout(i);
}, 15000);
}
}
});
ws.on('close', function close() {
console.log('disconnected SOCKET - PORT : 5000');
});
});
here in this example code of my programme you can see that it increment the value of iCounter
and return me after every 15 seconds...
so when it get this output, sometime it close the connection automatically. i sow some issue of same like this for websocket. and peoples say that websocket have some timeout so in npm ws
package socket, how can i increase the timeout. or is there any other issue for closing my websocket automatically???
first, sorry for my bad english..& please help me..
Upvotes: 2
Views: 5299
Reputation: 2815
First, what you need is: detecting reason why connection is closed. In onclose check event.code
. Check codes in https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
(check this on server and client)
Probably you need use on server ws.ping()
to maintaining the connection. (Some servers/proxies closse connection after 60s inactivity)
So, add in
serverConnection.on('connection',function(ws){
let interval = setInterval(function(){ws.ping()}, 50e3)
ws.on("close", function(ev) {
clearInterval(interval);
console.log('disconnected SOCKET - PORT : 5000, reason: ' + ev.code);
})
}
Close codes you can find here: https://github.com/Luka967/websocket-close-codes
Also in ev.reason
you can read more about it.
Upvotes: 5