107 lines
3.5 KiB
C#
107 lines
3.5 KiB
C#
using Chtn.CSharp.SDK.Core;
|
|
using Newtonsoft.Json;
|
|
using System;
|
|
using System.Net.Http;
|
|
using System.Net.Http.Headers;
|
|
using System.Net.WebSockets;
|
|
using System.Text;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Chtn.CSharpSDK.Core
|
|
{
|
|
public class WebSocketHandler
|
|
{
|
|
private static WebSocketHandler _instance;
|
|
private ClientWebSocket _webSocket;
|
|
private string _connectionId;
|
|
|
|
public event Action<string> OnNewConnectionId;
|
|
public event Action<string, string> OnPayloadReceived;
|
|
|
|
public static WebSocketHandler GetInstance()
|
|
{
|
|
if (_instance == null)
|
|
{
|
|
_instance = new WebSocketHandler();
|
|
}
|
|
return _instance;
|
|
}
|
|
|
|
public string ConnId => _connectionId;
|
|
|
|
public async Task ConnectAsync(string userId, string token)
|
|
{
|
|
var client = HttpClientFactory.CreateClient();
|
|
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token);
|
|
|
|
try
|
|
{
|
|
var response = await client.PostAsync("v2/ws/makeToken",
|
|
new StringContent(JsonConvert.SerializeObject(new { userid = userId }), Encoding.UTF8, "application/json"));
|
|
|
|
var content = await response.Content.ReadAsStringAsync();
|
|
var authData = JsonConvert.DeserializeObject<dynamic>(content);
|
|
|
|
string wsUrl = $"{EnvironmentConfig.Get().WsUrl}/vs/ws?userid={userId}&access_token={authData.token}";
|
|
|
|
_webSocket = new ClientWebSocket();
|
|
await _webSocket.ConnectAsync(new Uri(wsUrl), CancellationToken.None);
|
|
|
|
Console.WriteLine("Connected to websocket successfully");
|
|
|
|
_ = ReceiveLoop();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"Websocket hiba: {ex.Message}");
|
|
await Task.Delay(5000);
|
|
await ConnectAsync(userId, token);
|
|
}
|
|
}
|
|
|
|
private async Task ReceiveLoop()
|
|
{
|
|
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.Close)
|
|
{
|
|
await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
|
|
}
|
|
else
|
|
{
|
|
var message = Encoding.UTF8.GetString(buffer, 0, result.Count);
|
|
HandleIncomingMessage(message);
|
|
}
|
|
}
|
|
}
|
|
|
|
private void HandleIncomingMessage(string json)
|
|
{
|
|
try
|
|
{
|
|
var payload = JsonConvert.DeserializeObject<dynamic>(json);
|
|
string action = payload.action;
|
|
string data = JsonConvert.SerializeObject(payload.data);
|
|
|
|
if (action == "connectionId")
|
|
{
|
|
_connectionId = payload.data.connId;
|
|
OnNewConnectionId?.Invoke(_connectionId);
|
|
}
|
|
else
|
|
{
|
|
OnPayloadReceived?.Invoke(action, data);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"Payload feldolgozási hiba: {ex.Message}");
|
|
}
|
|
}
|
|
}
|
|
} |