54 lines
1.7 KiB
C#
54 lines
1.7 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 static WebSocketHandler GetInstance()
|
|
{
|
|
if (_instance == null)
|
|
{
|
|
_instance = new WebSocketHandler();
|
|
}
|
|
return _instance;
|
|
}
|
|
|
|
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");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"Websocket hiba: {ex.Message}");
|
|
}
|
|
}
|
|
}
|
|
} |