'C# ClientWebSocket doen't receive incoming messages until an outbound message is sent
I'm trying to receive messages from a server in real time, ideally using the ClientWebSocket class. I would like to both send and receive messages on their own. Unfortunately, I always first have to send an outgoing message through WebSocket.SendAsync() and only then new messages arrive with WebSocket.ReceiveAsync(). I tried searching and debugging the code but couldn't find anything that would fix this wrong behavior.
I would like to receive the incoming messages independently of me sending anything. Any help is be appreciated.
public static void WebsocketReceive()
{
while (WebSocket.State == WebSocketState.Open)
{
byte[] receiveBuffer = new byte[2048];
int offset = 0;
while (true)
{
try
{
ArraySegment<byte> bytesReceived = new(receiveBuffer, offset, receiveBuffer.Length);
WebSocketReceiveResult result = await WebSocket.ReceiveAsync(bytesReceived, source.Token);
offset += result.Count;
if (result.EndOfMessage) break;
}
catch { break; };
}
if (offset != 0)
{
Console.WriteLine(Encoding.UTF8.GetString(receiveBuffer, 0, offset));
}
}
}
Edit: more code
This is where I initialize the WebSocket and connect to a server. I don't have access to their code.
WebSocket = new ClientWebSocket();
await WebSocket.ConnectAsync(new Uri("wss://example.com"), Source.Token);
After connecting, I run my WebsocketReceive() method to start collecting incoming messages.
I send messages into the WebSocket from a different method, through this code:
await WebSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("message to post")), WebSocketMessageType.Text, true, Source.Token);
I should also provide some more details about how the client and server interact. At the start, I send and receive a few responses, which somehow works. I send some messages and receive responses, which are printed into the console.
What isn't working is specifically when the server wants to send me a message on its own. After a few seconds, I should receive incoming events from the server. This is where it stops printing into the console. Whenever I send any message again all of them come back at once - the loop is repeated for all messages in the "queue".
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
