-
Notifications
You must be signed in to change notification settings - Fork 3
/
WebSocketEventListener.cs
95 lines (83 loc) · 2.27 KB
/
WebSocketEventListener.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
using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using vtortola.WebSockets;
using vtortola.WebSockets.Rfc6455;
namespace WebSocketServer
{
public delegate void WebSocketEventListenerOnConnect(WebSocket webSocket);
public delegate void WebSocketEventListenerOnDisconnect(WebSocket webSocket);
public delegate void WebSocketEventListenerOnMessage(WebSocket webSocket, String message);
public delegate void WebSocketEventListenerOnError(WebSocket webSocket, Exception error);
public class WebSocketEventListener : IDisposable
{
public event WebSocketEventListenerOnConnect OnConnect;
public event WebSocketEventListenerOnDisconnect OnDisconnect;
public event WebSocketEventListenerOnMessage OnMessage;
public event WebSocketEventListenerOnError OnError;
readonly WebSocketListener _listener;
public WebSocketEventListener(IPEndPoint endpoint) : this(endpoint, new WebSocketListenerOptions())
{
}
public WebSocketEventListener(IPEndPoint endpoint, WebSocketListenerOptions options)
{
options.Standards.RegisterRfc6455();
_listener = new WebSocketListener(endpoint, options);
}
public void Start()
{
_listener.StartAsync().Wait();
}
public void Stop()
{
_listener.StopAsync().Wait();
}
public async Task ListenAsync()
{
while (_listener.IsStarted)
{
try
{
var websocket = await _listener.AcceptWebSocketAsync(CancellationToken.None).ConfigureAwait(false);
if (websocket != null)
Task.Run(() => HandleWebSocketAsync(websocket));
}
catch(Exception ex)
{
if (OnError != null)
OnError.Invoke(null, ex);
}
}
}
private async Task HandleWebSocketAsync(WebSocket websocket)
{
try
{
if (OnConnect != null)
OnConnect.Invoke(websocket);
while (websocket.IsConnected)
{
var message = await websocket.ReadStringAsync(CancellationToken.None).ConfigureAwait(false);
if (message != null && OnMessage != null)
OnMessage.Invoke(websocket, message);
}
if (OnDisconnect != null)
OnDisconnect.Invoke(websocket);
}
catch (Exception ex)
{
if (OnError != null)
OnError.Invoke(websocket, ex);
}
finally
{
websocket.Dispose();
}
}
public void Dispose()
{
_listener.Dispose();
}
}
}