Sachin
Sachin

Reputation: 182

websocket connection is closing automatically

i have deployed websocket server on heroku and Everything is working good but if there is no transfer between server and client after a certain time the connection is closed. i don't know who is closing the connection server or client and how to resolve this issue.

here is my node.js client code-

const Websocket = require('ws');

var ws = new Websocket('https://secure-mountain-02060.herokuapp.com/');

ws.onmessage = function(event){
console.log(event.data);
}

ws.onclose = function(){
console.log('server close');
}

Upvotes: 0

Views: 4586

Answers (1)

Sachin
Sachin

Reputation: 182

i found the solution server is closing the connection due to inactivity from client side. for that we have to ping the server after a certain time that time can be very depending upon the server.

This is how i have solved if anyone needs.

const Websocket = require('ws');

var  ws = new Websocket('https://secure-mountain-02060.herokuapp.com/');

function noop() {}

ws.onmessage = function(event){
  console.log(event.data);
}

ws.onclose = function(){
  console.log('server close');
}

const ping = function() {
  ws.ping(noop);
}

setInterval(ping, 30000);

Upvotes: 2

Related Questions