Websocket server sending spontaneous messages (without requests from the client)

892 Views Asked by At

I must admit I may have missed something fundamental. If so, please point it out. All that follows is how I understand a websocket server.

I'm trying to write a websocket server that should keep a client updated as to the status of a job they requested executed. There's an initial exchange in which the client identifies itself and sends a job ID, but since that moment essentially the client doesn't send any other message to the server. The server, as soon as it knows of an update in the status of its back-end, sends a message to the client, which reacts accordingly (usually no messages back).

This is my first websocket server, so I followed this sample by Microsoft as a reference: https://code.msdn.microsoft.com/The-simple-WebSocket-4524921c

The sample implements an echo server, that replies to client messages. Because of my different needs, I rewrote it so that the call to ReceiveAsync is called once, before the while loop. Inside the loop, my server checks its status, and sends the update messages if needed.

But, if I was to call ReceiveAsync in the while loop (where my update message logic is too), then the loop would be basically blocked: if I await to receive a message, but the client doesn't usually send any message, I'm effectively preventing my server from ever going to the next iteration of the loop. So I removed the call the ReceiveAsync: I don't expect messages, everything works fine.

My issue with this is that I'm not checking for Close messages, because I'm calling ReceiveAsync only once. Also, I don't have an actual full-duplex, which is fine by now, but this may change in the future (or for a different project).

So, on to actual questions:

1) Is it important to specifically wait for Close messages? Or can I assume that the websocket is automatically killed when the client's websocket object is destroyed?

2) How do I implement a full-duplex communication? In traditional sockets, I'd have an infinite loop, I'd check if there's something to read (construct the message, consume it, etc.), then if there is something to send to the client, then iterate: if there's nothing to read I would just go on. But ReceiveAsync seems to be the only method to receive data OR to check if there is any data, and if there's no data it just sits there and never completes.

Should I stop using System.Net.Websockets and move to a more featured library? All those I've found refer to "replying" to client messages, so I'm not sure they're suited to my needs (maybe it's just a case of poor examples and documentation).

0

There are 0 best solutions below