I'm using RealMarketAPI WebSocket to stream price data, but when the connection drops, it doesn't reconnect properly.
Here is my code:
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class Program
{
private static readonly Uri socketUri =
new Uri("wss://api.realmarketapi.com/price?apiKey=***&symbolCode=XAUUSD&timeFrame=H1");
static async Task Main()
{
while (true)
{
using (var ws = new ClientWebSocket())
{
await ws.ConnectAsync(socketUri, CancellationToken.None);
await ReceiveLoop(ws);
}
await Task.Delay(5000);
}
}
private static async Task ReceiveLoop(ClientWebSocket ws)
{
var buffer = new byte[4096];
while (ws.State == WebSocketState.Open)
{
var result = await ws.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
Console.WriteLine("Connection closed by server");
await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
break;
}
var message = Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine($"Received: {message}");
}
}
}
What is the correct way to handle reconnection or retries?