Squirrowse/squirrowse.client/ConnectionManager.cs

60 lines
1.5 KiB
C#
Raw Normal View History

2020-06-19 18:39:08 +02:00
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Client;
2020-06-20 14:00:42 +02:00
using Microsoft.Extensions.DependencyInjection;
2020-06-19 18:39:08 +02:00
namespace squirrowse.client
{
public class ConnectionManager : IConnectionManager
{
private readonly HubConnection _connection;
public bool Connected;
public ConnectionManager(string url, int port)
{
_connection = new HubConnectionBuilder()
.WithUrl($"{url}:{port}/hub")
.WithAutomaticReconnect()
2020-06-20 14:00:42 +02:00
.AddMessagePackProtocol()
2020-06-19 18:39:08 +02:00
.Build();
}
public async Task<HubConnection> GetConnection()
{
if (Connected) return _connection;
throw new Exception();
}
public async Task InitConnection()
{
if (_connection.State == HubConnectionState.Connected) return;
await _connection.StartAsync();
Connected = true;
}
public async Task Disconnect()
{
if (_connection.State == HubConnectionState.Disconnected) throw new Exception();
await _connection.StopAsync();
Connected = false;
}
public bool IsConnected()
{
return Connected;
}
}
public interface IConnectionManager
{
Task<HubConnection> GetConnection();
Task InitConnection();
Task Disconnect();
bool IsConnected();
}
}