Core logic ported from TS: HttpClientFactory, Environment and WebSocketHandler.
This commit is contained in:
56
Core/WebSocketHandler.cs
Normal file
56
Core/WebSocketHandler.cs
Normal file
@@ -0,0 +1,56 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Newtonsoft.Json;
|
||||
using System.Net.Http.Headers;
|
||||
using Chtn.CSharpSDK.Interfaces;
|
||||
using Chtn.CSharp.SDK.Core;
|
||||
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user