Websocket.Client 4.6.1
Websocket .NET client
This is a wrapper over native C# class ClientWebSocket
with built-in reconnection and error handling.
License:
MIT
Features
- installation via NuGet (Websocket.Client)
- targeting .NET Standard 2.0 (.NET Core, Linux/MacOS compatible) + Standard 2.1, .NET 5 and .NET 6
- reactive extensions (Rx.NET)
- integrated logging abstraction (LibLog)
- using Channels for high performance sending queue
Usage
var exitEvent = new ManualResetEvent(false);
var url = new Uri("wss://xxx");
using (var client = new WebsocketClient(url))
{
client.ReconnectTimeout = TimeSpan.FromSeconds(30);
client.ReconnectionHappened.Subscribe(info =>
Log.Information($"Reconnection happened, type: {info.Type}"));
client.MessageReceived.Subscribe(msg => Log.Information($"Message received: {msg}"));
client.Start();
Task.Run(() => client.Send("{ message }"));
exitEvent.WaitOne();
}
More usage examples:
Pull Requests are welcome!
Advanced configuration
To set some advanced configurations, which are available on the native ClientWebSocket
class,
you have to provide the factory method as a second parameter to WebsocketClient.
That factory method will be called on every reconnection to get a new instance of the ClientWebSocket
.
var factory = new Func<ClientWebSocket>(() => new ClientWebSocket
{
Options =
{
KeepAliveInterval = TimeSpan.FromSeconds(5),
Proxy = ...
ClientCertificates = ...
}
});
var client = new WebsocketClient(url, factory);
client.Start();
Also, you can access the current native class via client.NativeClient
.
But use it with caution, on every reconnection there will be a new instance.
Change URL on the fly
It is possible to change the remote server URL dynamically. Example:
client.Url = new Uri("wss://my_new_url");;
await client.Reconnect();
Reconnecting
A built-in reconnection invokes after 1 minute (default) of not receiving any messages from the server.
It is possible to configure that timeout via communicator.ReconnectTimeout
.
Also, a stream ReconnectionHappened
sends information about a type of reconnection.
However, if you are subscribed to low-rate channels, you will likely encounter that timeout - higher it to a few minutes or implement ping-pong
interaction on your own every few seconds.
In the case of a remote server outage, there is a built-in functionality that slows down reconnection requests
(could be configured via client.ErrorReconnectTimeout
, the default is 1 minute).
Beware that you need to resubscribe to channels after reconnection happens. You should subscribe to ReconnectionHappened
stream and send subscription requests.
Multi-threading
Observables from Reactive Extensions are single threaded by default. It means that your code inside subscriptions is called synchronously and as soon as the message comes from websocket API. It brings a great advantage of not to worry about synchronization, but if your code takes a longer time to execute it will block the receiving method, buffer the messages and may end up losing messages. For that reason consider to handle messages on the other thread and unblock receiving thread as soon as possible. I've prepared a few examples for you:
Default behavior
Every subscription code is called on a main websocket thread. Every subscription is synchronized together. No parallel execution. It will block the receiving thread.
client
.MessageReceived
.Where(msg => msg.Text != null)
.Where(msg => msg.Text.StartsWith("{"))
.Subscribe(obj => { code1 });
client
.MessageReceived
.Where(msg => msg.Text != null)
.Where(msg => msg.Text.StartsWith("["))
.Subscribe(arr => { code2 });
// 'code1' and 'code2' are called in a correct order, according to websocket flow
// ----- code1 ----- code1 ----- ----- code1
// ----- ----- code2 ----- code2 code2 -----
Parallel subscriptions
Every single subscription code is called on a separate thread. Every single subscription is synchronized, but different subscriptions are called in parallel.
client
.MessageReceived
.Where(msg => msg.Text != null)
.Where(msg => msg.Text.StartsWith("{"))
.ObserveOn(TaskPoolScheduler.Default)
.Subscribe(obj => { code1 });
client
.MessageReceived
.Where(msg => msg.Text != null)
.Where(msg => msg.Text.StartsWith("["))
.ObserveOn(TaskPoolScheduler.Default)
.Subscribe(arr => { code2 });
// 'code1' and 'code2' are called in parallel, do not follow websocket flow
// ----- code1 ----- code1 ----- code1 -----
// ----- code2 code2 ----- code2 code2 code2
Parallel subscriptions with synchronization
In case you want to run your subscription code on the separate thread but still want to follow websocket flow through every subscription, use synchronization with gates:
private static readonly object GATE1 = new object();
client
.MessageReceived
.Where(msg => msg.Text != null)
.Where(msg => msg.Text.StartsWith("{"))
.ObserveOn(TaskPoolScheduler.Default)
.Synchronize(GATE1)
.Subscribe(obj => { code1 });
client
.MessageReceived
.Where(msg => msg.Text != null)
.Where(msg => msg.Text.StartsWith("["))
.ObserveOn(TaskPoolScheduler.Default)
.Synchronize(GATE1)
.Subscribe(arr => { code2 });
// 'code1' and 'code2' are called concurrently and follow websocket flow
// ----- code1 ----- code1 ----- ----- code1
// ----- ----- code2 ----- code2 code2 ----
Async/Await integration
Using async/await
in your subscribe methods is a bit tricky. Subscribe from Rx.NET doesn't await
tasks,
so it won't block stream execution and cause sometimes undesired concurrency. For example:
client
.MessageReceived
.Subscribe(async msg => {
// do smth 1
await Task.Delay(5000); // waits 5 sec, could be HTTP call or something else
// do smth 2
});
That await Task.Delay
won't block stream and subscribe method will be called multiple times concurrently.
If you want to buffer messages and process them one-by-one, then use this:
client
.MessageReceived
.Select(msg => Observable.FromAsync(async () => {
// do smth 1
await Task.Delay(5000); // waits 5 sec, could be HTTP call or something else
// do smth 2
}))
.Concat() // executes sequentially
.Subscribe();
If you want to process them concurrently (avoid synchronization), then use this
client
.MessageReceived
.Select(msg => Observable.FromAsync(async () => {
// do smth 1
await Task.Delay(5000); // waits 5 sec, could be HTTP call or something else
// do smth 2
}))
.Merge() // executes concurrently
// .Merge(4) you can limit concurrency with a parameter
// .Merge(1) is same as .Concat() (sequentially)
// .Merge(0) is invalid (throws exception)
.Subscribe();
More info on Github issue.
Don't worry about websocket connection, those sequential execution via .Concat()
or .Merge(1)
has no effect on receiving messages.
It won't affect receiving thread, only buffers messages inside MessageReceived
stream.
But beware of producer-consumer problem when the consumer will be too slow. Here is a StackOverflow issue with an example how to ignore/discard buffered messages and always process only the last one.
Available for help
I do consulting, please don't hesitate to contact me if you have a custom solution you would like me to implement (web, m@mkotas.cz)
Showing the top 20 packages that depend on Websocket.Client.
.NET 5.0
- System.Reactive (>= 5.0.0)
- System.Threading.Channels (>= 5.0.0)
.NET 6.0
- System.Reactive (>= 5.0.0)
- System.Threading.Channels (>= 5.0.0)
.NET Standard 2.0
- System.Reactive (>= 5.0.0)
- System.Threading.Channels (>= 5.0.0)
.NET Standard 2.1
- System.Reactive (>= 5.0.0)
- System.Threading.Channels (>= 5.0.0)
Version | Downloads | Last updated |
---|---|---|
5.1.2 | 9 | 06/20/2024 |
5.1.1 | 53 | 04/15/2024 |
5.1.0 | 7 | 03/29/2024 |
5.0.0 | 5 | 04/27/2024 |
4.7.0 | 7 | 04/27/2024 |
4.6.1 | 8 | 04/27/2024 |
4.6.0 | 5 | 04/27/2024 |
4.5.2 | 4 | 04/27/2024 |
4.5.1 | 5 | 04/27/2024 |
4.5.0 | 4 | 04/27/2024 |
4.4.43 | 4 | 04/27/2024 |
4.4.42 | 5 | 04/27/2024 |
4.4.40 | 3 | 04/27/2024 |
4.4.39 | 5 | 04/27/2024 |
4.3.38 | 6 | 04/27/2024 |
4.3.36 | 4 | 04/27/2024 |
4.3.35 | 6 | 04/27/2024 |
4.3.32 | 3 | 04/27/2024 |
4.3.30 | 5 | 04/27/2024 |
4.3.21 | 4 | 04/27/2024 |
4.3.15 | 4 | 04/27/2024 |
4.3.14 | 5 | 04/27/2024 |
4.3.12 | 5 | 04/27/2024 |
4.2.11 | 4 | 04/27/2024 |
4.2.3 | 4 | 04/27/2024 |
4.1.85 | 6 | 04/27/2024 |
4.1.83 | 4 | 04/27/2024 |
4.1.82 | 7 | 04/27/2024 |
4.1.81 | 5 | 04/27/2024 |
4.1.79 | 6 | 04/27/2024 |
4.1.78 | 4 | 04/27/2024 |
4.1.77 | 5 | 03/30/2024 |
4.1.76 | 4 | 04/27/2024 |
4.1.75 | 5 | 04/27/2024 |
4.1.74 | 4 | 04/27/2024 |
4.1.73 | 5 | 04/27/2024 |
4.1.70 | 4 | 04/27/2024 |
4.1.69 | 5 | 04/27/2024 |
4.0.66 | 5 | 04/27/2024 |
3.2.61 | 6 | 04/27/2024 |
3.2.59 | 5 | 04/27/2024 |
3.2.56 | 6 | 04/27/2024 |
3.2.55 | 6 | 04/27/2024 |
3.2.54 | 4 | 04/27/2024 |
3.2.52 | 6 | 04/27/2024 |
3.1.32 | 5 | 04/27/2024 |
3.1.29 | 7 | 04/27/2024 |
3.1.28 | 7 | 04/16/2024 |
3.1.26 | 5 | 04/27/2024 |
3.1.25 | 4 | 04/27/2024 |
3.1.24 | 5 | 04/27/2024 |
3.0.23 | 5 | 04/27/2024 |
3.0.20 | 5 | 04/27/2024 |
3.0.19 | 5 | 04/27/2024 |
3.0.18 | 6 | 04/27/2024 |
3.0.17 | 5 | 04/27/2024 |
3.0.15 | 6 | 04/27/2024 |
2.0.10 | 5 | 04/27/2024 |
2.0.7 | 7 | 04/05/2024 |
1.0.6 | 5 | 04/27/2024 |
1.0.5 | 3 | 04/27/2024 |
1.0.4 | 3 | 04/27/2024 |
1.0.3 | 7 | 04/27/2024 |
1.0.2 | 6 | 04/27/2024 |
1.0.1 | 3 | 04/27/2024 |