Skip to content
WebSocket Client for C# (Unity and .NET Standard2.0 / 2.1) using Rx.
C# ShaderLab Other
Branch: master
Clone or download

Latest commit

Fetching latest commit…
Cannot retrieve the latest commit at this time.

Files

Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
Benchmark/Benchmark
Sample
Unity/UniWebSocket
netstandard
.gitignore
LICENSE
README.md

README.md

RxWebSocket

RxWebSocket is a WebSocket client for Unity and .NET Standard2.0/2.1. Since Unity 2018 supports .NET Standard 2.0, ClientWebSocket can be used. Therefore, WebSocket protocol can be used without an extra library. However, ClientWebSocket is very cumbersome. RxWebSocket is a wrapper of ClientWebSocket for easy handling. RxWebSocket was created with reference to the websocket-client (Released under the MIT License).

Tested platform(Unity)

  UWP iOS Mac OSX Standalone Windows10 Standalone
IL2CPP ⭕️ ⭕️    
Mono
(.NET Standard.0 & .NET 4.x)
    ⭕️ ⭕️
.NET Backend      

Download

Unity

Releases page

.NET Standard 2.0/2.1

dotnet add package RxWebSocket

Requirements for Unity

Usage

We prepared two classes.

  • WebSocketClient
    • it is common.
  • BinaryWebSocketClient
    • if you only send binary type, you can use this. BinaryWebSocketClient can send only binary type, but has less allocation.

Client

#if Unity
var webSocketClient = new WebSocketClient(new Uri("wss://~~~"), new UnityConsoleLogger());
//or
var binaryWebSocketClient = new BinaryWebSocketClient(new Uri("wss://~~~"), new UnityConsoleLogger());
#else 
Microsoft.Extensions.Logging.ILogger<T> logger;
var webSocketClient = new WebSocketClient(new Uri("wss://~~~"), logger.AsWebSocketLogger());
#endif

webSocketClient.BinaryMessageReceived
    .Subscribe(x => DoSomething(x));
    
webSocketClient.TextMessageReceived
    .Subscribe(x => DoSomething(x));

webSocketClient.CloseMessageReceived
    .Subscribe(x => DoSomething(x));

//Issued when an exception occurs in processing of the background thread(receiving and sending). 
webSocketClient.ExceptionHappened
    .Subscribe(x => DoSomething(x));


try
{
    //connect and start listening in background thread.
    //await until websocket can connect.
    await webSocketClient.ConnectAndStartListening();

    //send bin
    byte[] array = MakeSomeArray();
    webSocketClient.Send(array);

    //send text
    //The Send function guarantees the transmission order using queue.
    //It doesn't wait for the transmission to complete.
    webSocketClient.Send("string or byte[]");

    //The SendInstant function ignores the queue used inside the Send function and sends it immediately.
    //await for transmission to complete.
    await webSocketClient.SendInstant("string or byte[]");

    //You can decide whether to dispose at the same time as Close with the last bool parameter.
    await webSocketClient.CloseAsync(WebSocketCloseStatus.NormalClosure, "description", true);
}
catch
{
}

Server (ASP.NET Core)

HttpContext context;
Microsoft.Extensions.Logging.ILogger<T> logger;

if (!context.WebSockets.IsWebSocketRequest) return;

var socket = await context.WebSockets.AcceptWebSocketAsync();

using var webSocketClient = new WebSocketClient(socket, logger.AsWebSocketLogger());

// subscribe setting...

await webSocketClient.ConnectAndStartListening();

//If you do not wait, the connection will be disconnected.
await webSocketClient.Wait;

Here is sample.

Options

If you want to make detailed settings for WebSocket, use the factory method.

var factory = new Func<ClientWebSocket>(() => new ClientWebSocket
{
    Options =
    {
        KeepAliveInterval = TimeSpan.FromSeconds(5),
        Proxy = ...
        ClientCertificates = ...
    }
});

var webSocketClient = new WebSocketClient(url, factory);

The default received memory pool is set to 64KB. if lack of memory, memory pool is automatically increase so allocation occur. If it is known that a large size will come, it is advantageous to set a large memory pool in the following constructor.

public WebSocketClient(Uri url, int initialMemorySize, ILogger logger = null, Func<ClientWebSocket> clientFactory = null)

Notice

WebSocketClient issues all events from thread pool. Therefore, you cannot operate the components on Unity in Subscribe directly. So please handle from the main thread using an operator such as 'ObserveOnMainThread' as follows.

//error will occur.
webSocketClient.TextMessageReceived
    .Subscribe(x => unityObj.text = x);
    
//The following is correct.
webSocketClient.TextMessageReceived
    .ObserveOnMainThread()
    .Subscribe(x => unityObj.text = x);

Sample

I prepared a simple chat app as a sample. When the server starts, connect to ws://ip:port/ws.

Unity 2018

open this scene and run.

Server(C#/ ASP.NET Core3.1)

Requires .NET Core3.1. First, set your ip here. Then type the following command

$ cd Sample/Server/WebSocketChat/WebSocketChat/
$ dotnet run

Web(bonus)

open UniWebSocket/Sample/Web/WebSocketChat.html

You can’t perform that action at this time.