Как переподключиться к websocket?
Есть клиент websocket на c#. Он полноценно работает, в отдельных потоках крутятся методы получения данных, но через 3-4 часа сервер по каким-то причинам закрывает сокет. Вопрос как переподключиться к нему?
Попробовал отлавливать через try catch, но когда отваливается один сокек, то нормально происходит переподключение, а когда отваливается больше, программа зависает без ошибок.
Вызов:
Parallel.ForEach(pairs, pair => { new Thread(() => GetData("depth", pair)).Start(); });
Код Getdata:
private async Task GetData(string req, string pair)
{
CancellationTokenSource cancelTokenSource = new CancellationTokenSource();
CancellationToken token = cancelTokenSource.Token;
var client = new ClientWebSocket();
await client.ConnectAsync(new Uri(webSocketUri), token);
if (req.Equals("depth"))
{
string sym1 = getsym1(pair);
string sym2 = getsym2(pair);
Start_depth:
try
{
await client.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("{\"event\":\"sub\",\"params\":{\"channel\":\"market_" + pair + "_depth_step0\",\"cb_id\":\"" + pair + "\",\"asks\":1,\"bids\":1}}")), WebSocketMessageType.Text, true, token);
await Receiving(client, token, req, sym1, sym2);
}
catch(Exception e)
{
textBox3.Invoke((ThreadStart)delegate ()
{
textBox3.AppendText("Переподключаемся к websocket'у: " + pair + "\r\n");
});
goto Start_depth;
}
}
}
Код получения данных:
private static async Task Receiving(ClientWebSocket client, CancellationToken token, string req, string sym1, string sym2)
{
var buffer1 = new byte[8192];
var buffer = new ArraySegment<byte>(new byte[8192]);
if (req.Equals("depth"))
{
const string pattern = @"\[\[(.*?)\]";
Regex regex = new Regex(pattern);
string ask;
string bid;
string text;
string[] asks;
string[] bids;
List<string> _ask = new List<string> { "", "" };
List<string> _bid = new List<string> { "", "" };
Stopwatch sw = new Stopwatch();
while (true)
{
await client.ReceiveAsync(buffer, token);
buffer1 = DecompressZLibRaw(buffer.Array);
text = Encoding.UTF8.GetString(buffer1, 0, buffer1.Length);
Console.WriteLine(DateTime.Now + " " + text);
if (text.Contains("event_rep"))
{
var match = regex.Matches(text);
ask = match[0].Groups[1].Value;
bid = match[1].Groups[1].Value;
asks = ask.Split(',');
bids = bid.Split(',');
_ask[0] = asks[0];
_ask[1] = asks[1];
_bid[0] = bids[0];
_bid[1] = bids[1];
if (graph.ContainsKey(sym1))
{
graph[sym1][sym2] = _bid;
}
else
{
graph.Add(sym1, new Dictionary<string, List<string>>());
graph[sym1].Add(sym2, _bid);
}
if (graph.ContainsKey(sym2))
{
graph[sym2][sym1] = _ask;
}
else
{
graph.Add(sym2, new Dictionary<string, List<string>>());
graph[sym2].Add(sym1, _ask);
}
}
Console.WriteLine(DateTime.Now + " " + text);
}
}
}