The easiest way is to check if the socket is open or not before sending.
For example – write a simple function:
function isOpen(ws) { return ws.readyState === ws.OPEN }
Then – before any socket.send make sure it is open:
if (!isOpen(socket)) return;
socket.send(JSON.stringify(data));
You can also rewrite the send function like this answer but in my way you can log this situations.
And, for your second request
immediately attempt to connect again
There is no way you can do it from the server.
The client code should monitor the WebSocket state and apply reconnect method based on your needs.
For example – check this VueJS library that do it nicely. Look at Enable ws reconnect automatically section