Websocket Reconnecting in C# Using binance-connector-dotnet library

Hello! I need help using the binance-connector-dotnet library. More specificly the part where my interent stop or the websocket stop working for some reason and I need to reconnect it automatically. This is my code:

var symbol = “BTCUSDT”;
var numberOfBidsAndAsks = 5;
var updateSpeed = “1000ms”;
var isConnected = false;
while (true)
{
try
{
using (var websocket = new MarketDataWebSocket($"{symbol.ToLower()}@depth{numberOfBidsAndAsks}@{updateSpeed}"))
{
websocket.OnMessageReceived(
async (data) =>
{
Console.WriteLine(data);
}, CancellationToken.None);

        await websocket.ConnectAsync(CancellationToken.None);
        isConnected = true;
        Console.WriteLine("WebSocket connection established.");

        while (isConnected)
        {
            await Task.Delay(5000); // Check the connection status every 5 seconds
            //Logic to see if websocket is working then isConnected = false;
        }
    }
}
catch (Exception ex)
{
    Console.WriteLine($"WebSocket error: {ex.Message}");
}

Console.WriteLine("WebSocket connection lost. Reconnecting...");

await Task.Delay(5000); // Wait for 5 seconds before attempting to reconnect

}

I need help for this part:
while (isConnected)
{
await Task.Delay(5000); // Check the connection status every 5 seconds
//Logic to see if websocket is working then isConnected = false;
}

How to check if the connection is still on and it is working and if it is not working just to change the IsConnected to false and then try to connect again every 5 seconds.

Hello, I haven’t simulated a server disconnection for the snipped code below, however by understanding its logic, you should be able to test yourself.

Note:
For better WebSocket handling, you should create your own handler object by implementing IBinanceWebSocketHandler interface. In our Main code below, we named the handler CustomBinanceWebSocketHandler.cs, which has same code as BinanceWebSocketHandler.cs, but with:

        public async Task ConnectAsync(Uri uri, CancellationToken cancellationToken)
        {
            await this.webSocket.ConnectAsync(uri, cancellationToken);
            if (this.State == WebSocketState.Open)
            {
                Console.WriteLine("WebSocket connection established.");
            }    
        }

and

        public async Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer, CancellationToken cancellationToken)
        {
            WebSocketReceiveResult receiveResult = await this.webSocket.ReceiveAsync(buffer, cancellationToken);
            if (receiveResult.MessageType == WebSocketMessageType.Close)
            {
                Console.WriteLine("WebSocket Closed frame received");
            }

            return receiveResult;
        }

With CustomBinanceWebSocketHandler.cs created, we write the following Main code.

        public static async Task Main(string[] args)
        {
            try
            {
                IBinanceWebSocketHandler handler = new CustomBinanceWebSocketHandler(new ClientWebSocket());
                var websocket = new MarketDataWebSocket("btcusdt@aggTrade", handler);
                await websocket.ConnectAsync(CancellationToken.None);

                while (handler.State == WebSocketState.Open)
                {
                    try
                    {
                        websocket.OnMessageReceived(
                            async (result) =>
                        {
                            Console.WriteLine($"result: {result}");
                            await Task.CompletedTask;
                        }, CancellationToken.None);

                        await Task.Delay(3000); // 3s window to receive ws messages
                        handler.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Close", CancellationToken.None);
                        await Task.Delay(3000); // 3s window to detect the WebSocketMessageType.Close
                        
                    }
                    catch (WebSocketException ex)
                    {
                        Console.WriteLine($"WebSocket exception: {ex.Message}");
                    }
                }
            }
            catch (WebSocketException ex)
            {
                Console.WriteLine($"WebSocket exception: {ex.Message}");
            }
        }

The Disconnection should be detectable when receiveResult.MessageType == WebSocketMessageType.Close at handler or at WebSocketException sections.

This is just a code example, you can do any modifications that’s necessary for your own project.

1 Like

I would love the dotnet team to upload similar features for the library so can other people use it as well :slight_smile:

Small correction, there’s no features in provided code example, it’s just a demonstration on how to possibly handle Websocket locally according to what was wanted and using binance-connector-dotnet. This handling is a user-end management, therefore the connector doesn’t need have additional changes. :slight_smile: