Initial commit

This commit is contained in:
Thorbjoern
2025-05-26 00:46:28 +02:00
commit e5bca03433
3896 changed files with 1434297 additions and 0 deletions
Binary file not shown.
+231
View File
@@ -0,0 +1,231 @@
![Logo](https://raw.githubusercontent.com/Marfusios/websocket-client/master/websocket-logo.png)
# Websocket .NET client [![NuGet version](https://badge.fury.io/nu/Websocket.Client.svg)](https://www.nuget.org/packages/Websocket.Client) [![Nuget downloads](https://img.shields.io/nuget/dt/Websocket.Client)](https://www.nuget.org/packages/Websocket.Client)
This is a wrapper over native C# class `ClientWebSocket` with built-in reconnection and error handling.
[Releases and breaking changes](https://github.com/Marfusios/websocket-client/releases)
### License:
MIT
### Features
* installation via NuGet ([Websocket.Client](https://www.nuget.org/packages/Websocket.Client))
* targeting .NET Standard 2.0 (.NET Core, Linux/MacOS compatible) + Standard 2.1, .NET 5 and .NET 6
* reactive extensions ([Rx.NET](https://github.com/Reactive-Extensions/Rx.NET))
* integrated logging abstraction ([LibLog](https://github.com/damianh/LibLog))
* using Channels for high performance sending queue
### Usage
```csharp
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:
* integration tests ([link](test_integration/Websocket.Client.Tests.Integration))
* console sample ([link](test_integration/Websocket.Client.Sample/Program.cs))
* .net framework sample ([link](test_integration/Websocket.Client.Sample.NetFramework))
* blazor sample ([link](test_integration/Websocket.Client.Sample.Blazor))
**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`.
```csharp
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:
```chsarp
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.
```csharp
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.
```csharp
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:
```csharp
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:
```csharp
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:
```csharp
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
```csharp
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](https://github.com/dotnet/reactive/issues/459).
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](https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem) when the consumer will be too slow. Here is a [StackOverflow issue](https://stackoverflow.com/questions/11010602/with-rx-how-do-i-ignore-all-except-the-latest-value-when-my-subscribe-method-is/15876519#15876519)
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](http://mkotas.cz/),
<m@mkotas.cz>)
+7
View File
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: bd041495df58f2142b83447508fbcb20
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd">
<metadata>
<id>Websocket.Client</id>
<version>4.6.1</version>
<authors>Mariusz Kotas</authors>
<license type="expression">MIT</license>
<licenseUrl>https://licenses.nuget.org/MIT</licenseUrl>
<icon>icon.png</icon>
<readme>README.md</readme>
<projectUrl>https://github.com/Marfusios/websocket-client</projectUrl>
<iconUrl>https://raw.githubusercontent.com/Marfusios/websocket-client/master/src/Websocket.Client/icon.png</iconUrl>
<description>Client for websocket API with built-in reconnection and error handling</description>
<releaseNotes>Enhancements</releaseNotes>
<copyright>Copyright 2023 Mariusz Kotas. All rights reserved.</copyright>
<tags>websockets websocket client</tags>
<repository type="Git" url="https://github.com/Marfusios/websocket-client" />
<dependencies>
<group targetFramework="net5.0">
<dependency id="System.Reactive" version="5.0.0" exclude="Build,Analyzers" />
<dependency id="System.Threading.Channels" version="5.0.0" exclude="Build,Analyzers" />
</group>
<group targetFramework="net6.0">
<dependency id="System.Reactive" version="5.0.0" exclude="Build,Analyzers" />
<dependency id="System.Threading.Channels" version="5.0.0" exclude="Build,Analyzers" />
</group>
<group targetFramework=".NETStandard2.0">
<dependency id="System.Reactive" version="5.0.0" exclude="Build,Analyzers" />
<dependency id="System.Threading.Channels" version="5.0.0" exclude="Build,Analyzers" />
</group>
<group targetFramework=".NETStandard2.1">
<dependency id="System.Reactive" version="5.0.0" exclude="Build,Analyzers" />
<dependency id="System.Threading.Channels" version="5.0.0" exclude="Build,Analyzers" />
</group>
</dependencies>
</metadata>
</package>
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 47c37b34f0da3b5499e7adcfc4a2d166
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+3
View File
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:62782b2718ddc8c4d505baac320d681e7a590dd459a6fae48b9383325c27bc85
size 5481
+143
View File
@@ -0,0 +1,143 @@
fileFormatVersion: 2
guid: 3dc53fbc5f360b2418377bb8ee35ee32
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 13
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 1
mipBias: 0
wrapU: 0
wrapV: 0
wrapW: 0
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 4
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Android
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: WebGL
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
customData:
physicsShape: []
bones: []
spriteID:
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spriteCustomMetadata:
entries: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
userData:
assetBundleName:
assetBundleVariant:
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d8269a32fd1e4414db62f41855ec3aed
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 61993ca5c33e4a14e93db5a9a2546ac3
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,29 @@
fileFormatVersion: 2
guid: 63ddeb697f9f4d0478dbd5205465b79c
labels:
- NuGetForUnity
PluginImporter:
externalObjects: {}
serializedVersion: 3
iconMap: {}
executionOrder: {}
defineConstraints: []
isPreloaded: 0
isOverridable: 0
isExplicitlyReferenced: 0
validateReferences: 1
platformData:
Any:
enabled: 1
settings: {}
Editor:
enabled: 0
settings:
DefaultValueInitialized: true
WindowsStoreApps:
enabled: 0
settings:
CPU: AnyCPU
userData:
assetBundleName:
assetBundleVariant:
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 21c27b8e533a1664897016d06391ead6
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant: