Reputation: 81
I'm currently working on a System.Net.WebSockets
implementation that will be using cellular networks to send data packets about the device in a real-time manner. Using cellular network means that my solution should be able to reconnect a socket when the network occasionally loses connection. The only way that I have been able to do this is by creating a new instance of the ClientWebSocket
and then sending the connect message asynchronously.
This is not my exact code but hopefully it will get the idea across of what I am trying to do.
void PublisherConnect()
{
myWebSocket = new ClientWebSocket();
Task.Run(async () =>
{
if (myWebSocket.ConnectionState != WebSocketState.Open)
{
try
{
await myWebSocket.ConnectAsync(HostString);
}
catch (WebSocketException ee)
{
Debug.WriteLine(ee.Message);
}
}
}
}
internal async Task ConnectAsync(Uri uri)
{
using (var cts = new CancellationTokenSource())
{
try
{
await myWebSocket.ConnectAsync(uri, CancellationToken.None);
manualState = false;
}
catch (Exception)
{
throw;
}
}
}
If I try to connect again with the same object after a clean disconnect, an error is thrown with the message, "The websocket has already been started." What is it about WebSockets that I don't understand?
EDIT - I am building this into a NuGet package to be used as a library for other apps so I need to stay around .NET 4.6 due to how the programs that will be consuming this function.
Upvotes: 8
Views: 4023