Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper reconnect after WebSocketException

I use ClientWebSocket to connect to a socket server. If I stop the server I got WebSocketException what is OK. Then I try to reconnect.

If I use

await wsClient.ConnectAsync(serviceUri, cts.Token);

I get "System.InvalidOperationException: 'The WebSocket has already been started.'"

If I try to close it before reconnecting by

await wsClient.CloseAsync(WebSocketCloseStatus.Empty, string.Empty, CancellationToken.None);

I get "System.Net.WebSockets.WebSocketException: 'The WebSocket is in an invalid state ('Aborted') for this operation. Valid states are: 'Open, CloseReceived, CloseSent'' "

So what is the proper way of reconnecting after the connection has been lost.

like image 453
amplifier Avatar asked Feb 04 '26 22:02

amplifier


1 Answers

I've just run into the same problem. Apparently you cannot reuse an aborted ClientWebSocket. The docs of ClientWebSocket.Abort() say:

The ClientWebSocket cannot be reused once it is aborted.

like image 54
EagleBeak Avatar answered Feb 06 '26 10:02

EagleBeak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!