-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathUDPer.cs
More file actions
88 lines (80 loc) · 2.37 KB
/
Copy pathUDPer.cs
File metadata and controls
88 lines (80 loc) · 2.37 KB
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
using System;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;
namespace UDPer
{
class UDPer
{
const int PORT_NUMBER = 15000;
Thread t = null;
public void Start()
{
if (t != null)
{
throw new Exception("Already started, stop first");
}
Console.WriteLine("Started listening");
StartListening();
}
public void Stop()
{
try
{
udp.Close();
Console.WriteLine("Stopped listening");
}
catch { /* don't care */ }
}
private readonly UdpClient udp = new UdpClient(PORT_NUMBER);
IAsyncResult ar_ = null;
private void StartListening()
{
ar_ = udp.BeginReceive(Receive, new object());
}
private void Receive(IAsyncResult ar)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any, PORT_NUMBER);
byte[] bytes = udp.EndReceive(ar, ref ip);
string message = Encoding.ASCII.GetString(bytes);
Console.WriteLine("From {0} received: {1} ", ip.Address.ToString(), message);
StartListening();
}
public void Send(string message)
{
UdpClient client = new UdpClient();
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("255.255.255.255"), PORT_NUMBER);
byte[] bytes = Encoding.ASCII.GetBytes(message);
client.Send(bytes, bytes.Length, ip);
client.Close();
Console.WriteLine("Sent: {0} ", message);
}
}
class Program
{
static void Main(string[] args)
{
UDPer udp = new UDPer();
udp.Start();
ConsoleKeyInfo cki;
do
{
if (Console.KeyAvailable)
{
cki = Console.ReadKey(true);
switch (cki.KeyChar)
{
case 's':
udp.Send(new Random().Next().ToString());
break;
case 'x':
udp.Stop();
return;
}
}
Thread.Sleep(10);
} while (true);
}
}
}