Hello, I have a question regarding using WebSocket in a .NET 6 environment to connect to Binance and retrieve contract prices. I’ve implemented a mechanism to periodically reconnect the WebSocket, but after re-establishing the connection, I’ve noticed that I’m no longer receiving the information that the WebSocket should be transmitting. Any insights or suggestions would be greatly appreciated.
public class BinanceHelper
{
private ClientWebSocket _webSocket = new ClientWebSocket();
private string _webSocketEndpoint = string.Empty;
private readonly string _binanceWsEndpoint = $"wss://fstream.binance.com/stream?streams=";
private System.Timers.Timer _reconnectTimer;
public BinanceHelper()
{
_reconnectTimer = new System.Timers.Timer(3600000);
_reconnectTimer.Elapsed += async (sender, e) => await AutoReconnectAsync();
_reconnectTimer.AutoReset = true;
}
public async Task ConnectAsync()
{
_reconnectTimer.Start();
Program.Logger.Info("開始連接WebStocket連線");
string btc = "btcusdt@aggTrade";
string eth = "ethusdt@aggTrade";
string sol = "solusdt@aggTrade";
_webSocketEndpoint = $"{_binanceWsEndpoint}{btc}/{eth}/{sol}";
await _webSocket.ConnectAsync(new Uri(_webSocketEndpoint), CancellationToken.None);
if (_webSocket.State == WebSocketState.Open)
{
Program.Logger.Info("WebStocket連線成功");
}
}
public async Task ReceiveMessagesAsync()
{
var buffer = new byte[1024 * 4];
while (_webSocket.State == WebSocketState.Open)
{
var result = await _webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Text)
{
var response = Encoding.UTF8.GetString(buffer, 0, result.Count);
}
Array.Clear(buffer, 0, buffer.Length);
}
}
private async Task AutoReconnectAsync()
{
if (_webSocket.State == WebSocketState.Open)
{
await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Close", CancellationToken.None);
Program.Logger.Info("每小時自動關閉WebStocket連線");
await ReconnectAsync();
}
}
public async Task ReconnectAsync()
{
_webSocket?.Dispose();
_webSocket = new ClientWebSocket();
await ConnectAsync();
if (_webSocket.State == WebSocketState.Open)
{
await _telegramHelper.SendWebStocketMsg("Stocket連線建立成功");
break;
}
}
}
Log
2024-01-10 14:28:14.0662 | INFO | Program | 每小時自動關閉WebStocket連線
2024-01-10 14:28:22.1048 | INFO | Program | 開始進行重新連接WebStocket連線流程
2024-01-10 14:29:58.6862 | INFO | Program | 釋放Stocket連線資源,重新建立執行個體
2024-01-10 14:30:09.6541 | INFO | Program | 開始連接WebStocket連線
2024-01-10 14:30:35.6748 | INFO | Program | WebStocket連線成功