I was trying to implement a chat app using W3Csocket in ReactJs (class component). The issue is the socket disconnects due to various reasons. I want the socket to reconnect whenever it disconnects so that the chat app works even when it is open in the browser window for a long time.
I am connecting the socket in constructor like:-
constructor(props){
super(props);
this.state= {
client: new W3CWebSocket(socket_url)
}
}
here is the code used to listen to messages.
this.state.client.onmessage = (message) => {
console.log("Socket recieved message...");
};
here is the code I had implemented to reconnect the socket.
this.state.client.onclose = (e) => {
console.log("Socket closed...");
this.setState({client: new W3CWebSocket(socket_url)});
};