-
Notifications
You must be signed in to change notification settings - Fork 24
/
UdpListener.cs
101 lines (88 loc) · 2.61 KB
/
UdpListener.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
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace KeePassNatMsg.Protocol.Listener
{
public sealed class UdpListener : IDisposable
{
private readonly Thread _thread;
private UdpClient _client;
private IPEndPoint _ep;
private volatile bool _active;
private readonly System.Text.UTF8Encoding _utf8 = new System.Text.UTF8Encoding(false);
private readonly int _port;
public event EventHandler<UdpMessageReceivedEventArgs> MessageReceived;
public UdpListener(int port)
{
_port = port;
_thread = new Thread(new ThreadStart(Run))
{
Name = $"{GetType().Name}_Thread"
};
}
public void Start()
{
if (_thread.ThreadState == ThreadState.Unstarted)
{
_active = true;
_thread.Start();
}
}
public void Stop()
{
_active = false;
_client.Close();
_thread.Join();
}
public void Send(string msg, IPEndPoint ep)
{
var data = _utf8.GetBytes(msg);
_client.Send(data, data.Length, ep);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing)
{
// dispose managed resources
_client.Close();
}
// free native resources
}
private void Run()
{
_ep = new IPEndPoint(IPAddress.Any, _port);
_client = new UdpClient(_ep);
while (_active)
{
var ar = _client.BeginReceive(ReceiveData, null);
ar.AsyncWaitHandle.WaitOne();
}
}
private void ReceiveData(IAsyncResult ar)
{
if (_active)
{
var ep = new IPEndPoint(IPAddress.Any, 0);
var data = _client.EndReceive(ar, ref ep);
var str = System.Text.Encoding.UTF8.GetString(data);
MessageReceived?.Invoke(this, new UdpMessageReceivedEventArgs(ep, str));
}
}
}
public sealed class UdpMessageReceivedEventArgs: EventArgs
{
public IPEndPoint From { get; private set; }
public string Message { get; private set; }
public UdpMessageReceivedEventArgs(IPEndPoint from, string msg)
{
From = from;
Message = msg;
}
}
}