websocket is shutting down due to PHP idle

Question:

There are problems with the websocket. It works fine, everything is super, but if no one uses the socket for more than 1 minute, it turns off. After a minute of inactivity, I receive a "CloseEvent" with the code "1000" for any request. When at least one user is connected, the problem is solved by ping-pong, but when there is no user, the socket hangs idle. It seems that I have already indicated all the configurations related to the timeout, but it did not help.

The socket is implemented using the library: https://github.com/pmill/php-chat

Checked on Open Server. Used by Apache in conjunction with Nginx.

Answer:

There are 2 ways to solve this problem: 1) For the server to ping every 30 seconds (any interval, less than 1 minute) 2) Implement the reconnect function on the client if the connection is reconnect or reconnect by interval.

Here is an example implementation of reconnect . You can also use other libraries that do reconnect under the hood.

const WebSocket = require('ws');

function WebSocketClient(){
	this.number = 0;	// Message number
	this.autoReconnectInterval = 5*1000;	// ms
}
WebSocketClient.prototype.open = function(url){
	this.url = url;
	this.instance = new WebSocket(this.url);
	this.instance.on('open',()=>{
		this.onopen();
	});
	this.instance.on('message',(data,flags)=>{
		this.number ++;
		this.onmessage(data,flags,this.number);
	});
	this.instance.on('close',(e)=>{
		switch (e.code){
		case 1000:	// CLOSE_NORMAL
			console.log("WebSocket: closed");
			break;
		default:	// Abnormal closure
			this.reconnect(e);
			break;
		}
		this.onclose(e);
	});
	this.instance.on('error',(e)=>{
		switch (e.code){
		case 'ECONNREFUSED':
			this.reconnect(e);
			break;
		default:
			this.onerror(e);
			break;
		}
	});
}
WebSocketClient.prototype.send = function(data,option){
	try{
		this.instance.send(data,option);
	}catch (e){
		this.instance.emit('error',e);
	}
}
WebSocketClient.prototype.reconnect = function(e){
	console.log(`WebSocketClient: retry in ${this.autoReconnectInterval}ms`,e);
        this.instance.removeAllListeners();
	var that = this;
	setTimeout(function(){
		console.log("WebSocketClient: reconnecting...");
		that.open(that.url);
	},this.autoReconnectInterval);
}
WebSocketClient.prototype.onopen = function(e){	console.log("WebSocketClient: open",arguments);	}
WebSocketClient.prototype.onmessage = function(data,flags,number){	console.log("WebSocketClient: message",arguments);	}
WebSocketClient.prototype.onerror = function(e){	console.log("WebSocketClient: error",arguments);	}
WebSocketClient.prototype.onclose = function(e){	console.log("WebSocketClient: closed",arguments);	}

var wsc = new WebSocketClient();
wsc.open('wss://localhost:8080/');
wsc.onopen = function(e){
	console.log("WebSocketClient connected:",e);
	this.send("Hello World !");
}
wsc.onmessage = function(data,flags,number){
	console.log(`WebSocketClient message #${number}: `,data);
}
Scroll to Top