Prevent WebSocket Server Close Event with MSW

Sicne we're involving an actual WebSocket server in our mock, what happens if that server disconnects? Well, the client connection will close, which is a bummer. Let's see how to listen and prevent original server's close event, and also conditionally fallback to MSW to act as the server if that happens.

Resources

Share with a coworker

Social Share Links

Transcript

[00:00] It looks like our original WebSocket server is having trouble connecting our client. Because we've established the actual server connection by calling server.connect, all the events, including the close event, are forwarded from the server to the client. But that shouldn't stop us from developing our application. Let's add a CloseEventListener to the server by calling server.AddEventListener, providing close as the event name, and adding the listener function. This function will be called whenever the actual server is closing the connection.

[00:31] We can grab the event reference from the argument and call event.preventDefault. Calling this preventDefault method on the close event will prevent the propagation of this event to the client that will result in closing the connection. So with these changes we can see that our WebSocket client is active because we can type something in the chat. But if we do, nothing is actually displayed. Well that is because we're forwarding the client messages to the actual server over here, and since the server is closed it cannot respond with any event back.

[01:03] So let's improve this logic. We can check if the server is operational by accessing the server.socket instance. This is a raw WebSocket instance that represents the connection to the actual server. And we can check its ready state property that represents in which state this WebSocket connection is in. If it's in a state bigger than WebSocket.open, which means closing or closed states, let's instead forward this message from the client back to the client, basically making MSW act as the server.

[01:33] And if the server is operational, let's keep forwarding to the actual server as is. So now if I send a message, I can see that message displayed in the UI because although the server is closed, we are using MSW as the server sending this message back to the client.