I have a connection to the Websocket server, which should be there for 40 seconds or so. Ideally, this should be forever open.
The client constantly sends data to the server and vice versa.
I am using this sequence now:
var socket; function senddata(data) { if (!socket) { socket = new WebSocket(url); socket.onopen = function (evt) { socket.send(data); socket.onmessage = function (evt) { var obj = JSON.parse(evt.data); port.postMessage(obj); } socket.oneerror = function (evt) { socket.close(); socket = null; } socket.onclose = function(evt){ socket = null; } } } else { socket.send(data); } }
Obviously, according to the current logic, in case of an error, the current request data may not be sent at all.
To be honest, sometimes an error occurs that the websocket is still in a connected state. This connection often breaks due to network problems. In short, this does not work perfectly.
I read the best design: How to wait for ReadyState for WebSocket to change , but does not cover all the cases that I need to handle.
I also thought about it, but could not get the correct procedure for this.
So, what is the correct way to send regular data through Websockets, which does a good job of problems like disconnection, etc.
javascript websocket
user5858
source share