-
Notifications
You must be signed in to change notification settings - Fork 0
/
RecognitionServiceServer.cs
103 lines (81 loc) · 2.44 KB
/
RecognitionServiceServer.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
using System;
using System.Diagnostics;
using Newtonsoft.Json.Linq;
using WebSocketSharp;
using WebSocketSharp.Server;
namespace RecognitionService.Api
{
public class RecognitionServiceServer : IDisposable
{
private readonly WebSocketServer _webSocketServer;
public event Func<int[]> OnMarkerListRequested;
public event Action<int, Triangle> OnRegisterMarkerRequested;
public event Action<int> OnUnregisterMarkerRequested;
public bool HasConnections => _webSocketServer.WebSocketServices.SessionCount > 0;
public RecognitionServiceServer(int port)
{
_webSocketServer = new WebSocketServer(port);
_webSocketServer.AddWebSocketService("/", () => new MessageResponder(this));
_webSocketServer.Start();
}
public void Dispose() => _webSocketServer.Stop();
private class MessageResponder : WebSocketBehavior
{
private readonly RecognitionServiceServer _server;
public MessageResponder(RecognitionServiceServer server)
{
_server = server;
}
protected override void OnMessage(MessageEventArgs e)
{
try
{
Debug.WriteLine("Received message");
if (e.IsText)
{
(var type, var payload) = ApiHelpers.ParseMessage(e.Data);
switch (type)
{
case ApiEvent.RequestList:
HandleMarkerListRequest();
break;
case ApiEvent.RegisterMarker:
HandleMarkerRegisterRequest(payload);
break;
case ApiEvent.UnregisterMarker:
HandleMarkerUnregisterRequest(payload);
break;
default:
throw new NotSupportedException();
}
}
else
throw new NotSupportedException();
}
catch (Exception exception)
{
Debug.WriteLine($"Exception:{exception.Message}");
}
}
private void HandleMarkerRegisterRequest(JToken payload)
{
Debug.WriteLine("Register requested");
var requestArgs = payload.ToObject<ApiHelpers.RegisterMarkerRequestArgs>();
_server?.OnRegisterMarkerRequested(requestArgs.id, requestArgs.triangle);
}
private void HandleMarkerUnregisterRequest(JToken payload)
{
Debug.WriteLine("Unregister requested");
var id = payload.ToObject<int>();
_server.OnUnregisterMarkerRequested?.Invoke(id);
}
private void HandleMarkerListRequest()
{
Debug.WriteLine("List requested");
var list = _server.OnMarkerListRequested?.Invoke();
var message = ApiHelpers.CreateMessage(ApiEvent.ResponseList, list);
Send(message.ToString());
}
}
}
}