-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathUdpNotifier.cs
48 lines (42 loc) · 1.17 KB
/
UdpNotifier.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace DigitalPlatform.IO
{
/// <summary>
/// UDP 广播通知
/// </summary>
public class UdpNotifier
{
UdpClient udpClient = new UdpClient();
int PORT = 9876;
public delegate void Delegate_notify(string message);
public void StartListening(Delegate_notify func)
{
udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, PORT));
var from = new IPEndPoint(0, 0);
Task.Run(() =>
{
while (true)
{
var recvBuffer = udpClient.Receive(ref from);
func?.Invoke(Encoding.UTF8.GetString(recvBuffer));
}
});
}
public void StopListening()
{
udpClient.Dispose();
}
public void Notify(string message)
{
var data = Encoding.UTF8.GetBytes(message);
udpClient.Send(data, data.Length, "255.255.255.255", PORT);
}
}
}