I’m using the System.Net.WebSockets.ClientWebSocket class in C# .NET 6.0.
I have a timer set up that repeatedly will poll the websocket for connections, shown here. The timer is elapsed every 16 ms.
When the packet is recieved, it’ll deserialize it as JSON and create an event. This works, but it only does it once.
I added the print lines for testing: Console.WriteLine(“Awaiting started”) and Console.WriteLine(“Awaiting ended”). Awaiting started should be printed when the websocket is polled. It should print Awaiting ended after the websocket has finished the polling, and then if the packet recieved isn’t empty, it’ll deserialize it.
private async void poll(Object? sender, ElapsedEventArgs event_args) {
switch (web_socket.State) {
case WebSocketState.Open: {
if (socket_connected == false) {
socket_connected = true;
}
try {
// RecieveAsync automatically polls and recieves the packet.
Memory<Byte> memory = new Memory<Byte>(new Byte[1024]);
Console.WriteLine("Awaiting started");
ValueWebSocketReceiveResult result = await web_socket.ReceiveAsync(memory, CancellationToken.None);
Console.WriteLine("Awaiting ended");
// Only attempt deserialization if a packet was recieved, aka the buffer is not empty.
if (result.Count != 0) {
deserialize_event(memory.Slice(0, result.Count).ToArray());
}
} catch (Exception exception) {
Console.WriteLine("Pusher polling error: " + exception.ToString());
}
} break;
case WebSocketState.Closed: {
connection_closed(web_socket.CloseStatus);
} break;
}
}
What’s supposed to happen: It should first print that its awaiting, then await the packet, then write the contents to the buffer, then move on with the execution, printing that the Await ended.
What actually happens:It only prints “Awaiting Ended” one singular time
It looks like it only recieves one singular packet, and then all calls to RecieveAsync never finish.
FireCatMagic is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.