I am working on an C# Asp.NET Core app where clients will connect via a JavaScript WebSocket to the server and the server itself will be the only thing that can send messages to the connected clients.
The clients will not be sending messages back to the server and if they manage to send a message to the server by manually doing so in any browser console, the server will just ignore them.
This is a sample of the C# code I am using to send messages to all connected clients:
foreach(WebSocket webSocket in WebsocketHandler.WebSocketClients.Values)
{
await webSocket.SendAsync(...);
}
Since I am not expecting clients to send messages back to the server (since this is supposed to be a one-way message flow), is a subsequent call to:
await webSocket.ReceiveAsync(...);
immediately after a call to "SendAysnc()" required at all? Are their downsides/consequences to not calling "ReceiveAsync()" after calling "SendAsync()"?
I could not find anything in the documentation from MS that says it is required to call "ReceiveAsync" after calling "SendAsync()" (though most online examples do) and both methods (according to MS documentation) state that "This operation will not block."
My primary concern here with this is whether or not continuously only sending messages and not receiving anything back may either cause a memory leak from many "SendAsync()" calls piling up because it expects some "response" back or the server disconnecting a client(s) because no message is being sent back from the other side of the communication channel and the server thinks the client has dropped.
Regards.
You need to call ReceiveAsync so you can detect when the websocket closes so you can complete the close handshake. Generally when using websockets directly, you'll have 2 async loops running in parallel, the receive loop and send loop (or you can hand off the socket to send like you are doing). You also need to make sure the request that did the websocket upgrade keeps running so that the connection doesn't get closed and in your scenario, you can use the receive loop for that purpose.