Logo
Blog

Timeline

Blog

Reactive Websocket – portable client websocket implementation with Rx support

Web-sockets are the latest addition to the communication protocol which standardizes the way client communicates with the server. It provides full duplex communication channel over a single TCP connection which is great considering the workarounds that existed previously for achieving the same result.

For .Net world, Microsoft has provided a client implementation of Websocket which can connect to any server supporting the same protocol. However, it as a much lower level leaving the developer to deal with a lot of boilerplate code, not to mention effort which goes in making the code robust.

Reactive websocket is an open source library which has been developed as a wrapper of the Microsoft’s implementation providing the following functionalities:

  1. Based on portable library, supports desktop and android client. Other platforms coming soon.
  2. Built in Rx support. Supports both request-response and streaming style of communication.
  3. Supports simple string as well as custom message serialization/deserialization. JSON support coming next.
  4. Completely asynchronous API with no performance bottleneck at all.
  5. Built in exception handling and status reporting.
  6. Supports multiple message type/format on the same stream

Usage

The API is very easy to use. Firstly, you should decide what is your communication and message type. Whether it is string, json or your custom implementation. Also, is the message going to be always in a particular format or can it change based on the method call.

Let’s say you have a very simple requirement and the server and client communicates using string objects only. You can initialize a StringWebsocketClient which will serves the purpose. (Note that you can also use JSON in your application code by deserializing and serializing yourself however JSON inbuilt support is coming soon). Initialization is as simple as calling the constructor.

After you have selected the right client, you need to connect to the server which supports websockets.

 

Then, based on type of API call you can call two types of methods. If it is request response type where you only expect the result to be sent once, then use the following.

Note that the second parameter specifies a predicate to filter out the responses. Here we would get all the responses from the server even if it is a result of some previous method call. You should ideally have a mechanism in your application code to identify and correlate the results. For example setting an Id field in the request and using the same Id to populate the result object on server side.

If you expect a stream of response from the server, you can use the following:

 

To subscribe to the connection status and error :

 

Leave A Comment