51 lines
1.5 KiB
C#
51 lines
1.5 KiB
C#
using System;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.SignalR.Client;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Squirrowse.Core.Models;
|
|
|
|
namespace Squirrowse.Core.Services
|
|
{
|
|
public class ConnectionManager : IConnectionManager
|
|
{
|
|
private readonly HubConnection _connection;
|
|
private bool Connected;
|
|
|
|
public ConnectionManager(string url, int port)
|
|
{
|
|
_connection = new HubConnectionBuilder()
|
|
.WithUrl($"{url}:{port}/StreamHub")
|
|
.AddMessagePackProtocol()
|
|
.WithAutomaticReconnect()
|
|
.Build();
|
|
}
|
|
|
|
public async Task<HubConnection> GetConnection()
|
|
{
|
|
return _connection;
|
|
}
|
|
|
|
public async Task InitConnection(ConnectionType type)
|
|
{
|
|
if (_connection.State == HubConnectionState.Connected) return;
|
|
if (_connection.State == HubConnectionState.Disconnected) await _connection.StartAsync();
|
|
|
|
await RegisterOnHub(type);
|
|
Connected = true;
|
|
|
|
}
|
|
|
|
|
|
public async Task Disconnect()
|
|
{
|
|
if (_connection.State == HubConnectionState.Disconnected) throw new Exception();
|
|
await _connection.StopAsync();
|
|
Connected = false;
|
|
}
|
|
|
|
private async Task RegisterOnHub(ConnectionType type)
|
|
{
|
|
await _connection.SendAsync("AddUser", Environment.UserName, type);
|
|
}
|
|
}
|
|
} |