-
Notifications
You must be signed in to change notification settings - Fork 51
/
StrategyNotificationHub.cs
81 lines (65 loc) · 2.9 KB
/
StrategyNotificationHub.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using DevelopmentInProgress.Socket.Messages;
using DevelopmentInProgress.Socket.Server;
using DevelopmentInProgress.TradeServer.StrategyExecution.WebHost.Notification.Server;
using Newtonsoft.Json;
using System;
using System.Net.WebSockets;
using System.Threading.Tasks;
namespace DevelopmentInProgress.TradeServer.StrategyExecution.WebHost.Notification.Strategy
{
public class StrategyNotificationHub : SocketServer, IServerNotification
{
public StrategyNotificationHub(ConnectionManager connectionManager, ChannelManager channelManager)
: base(connectionManager, channelManager)
{
}
public event EventHandler<ServerNotificationEventArgs> ServerNotification;
public async override Task OnClientConnectAsync(WebSocket websocket, string clientId, string strategyName)
{
if (string.IsNullOrWhiteSpace(clientId))
{
throw new ArgumentNullException(nameof(clientId));
}
if(string.IsNullOrWhiteSpace(strategyName))
{
throw new ArgumentNullException(nameof(strategyName));
}
var connection = await base.AddWebSocketAsync(websocket).ConfigureAwait(false);
connection.Name = clientId;
SubscribeToChannel(strategyName, websocket);
var connectionInfo = connection.GetConnectionInfo();
var json = JsonConvert.SerializeObject(connectionInfo);
var message = new Message { MethodName = "OnConnected", SenderConnectionId = "StrategyRunner", Data = json };
await SendMessageAsync(websocket, message).ConfigureAwait(false);
OnServerNotification();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types")]
public async override Task ReceiveAsync(WebSocket webSocket, Message message)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
try
{
switch (message.MessageType)
{
case MessageType.UnsubscribeFromChannel:
UnsubscribeFromChannel(message.Data, webSocket);
break;
}
OnServerNotification();
}
catch (Exception ex)
{
var errorMessage = new Message { MethodName = message.MethodName, SenderConnectionId = message.SenderConnectionId, Data = $"{MessageType.UnsubscribeFromChannel} Error : {ex.Message}" };
await SendMessageAsync(webSocket, errorMessage).ConfigureAwait(false);
}
}
private void OnServerNotification()
{
var serverNotification = ServerNotification;
serverNotification?.Invoke(this, new ServerNotificationEventArgs());
}
}
}