-
Notifications
You must be signed in to change notification settings - Fork 550
/
Program.cs
115 lines (97 loc) · 3.33 KB
/
Program.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
104
105
106
107
108
109
110
111
112
113
114
115
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using NetCoreServer;
using NDesk.Options;
namespace UdpEchoServer
{
class EchoServer : UdpServer
{
public EchoServer(IPAddress address, int port) : base(address, port) {}
protected override void OnStarted()
{
// Start receive datagrams
ReceiveAsync();
}
protected override void OnReceived(EndPoint endpoint, byte[] buffer, long offset, long size)
{
// Continue receive datagrams.
if (size == 0)
{
// Important: Receive using thread pool is necessary here to avoid stack overflow with Socket.ReceiveFromAsync() method!
ThreadPool.QueueUserWorkItem(o => { ReceiveAsync(); });
}
// Echo the message back to the sender
SendAsync(endpoint, buffer, offset, size);
}
protected override void OnSent(EndPoint endpoint, long sent)
{
// Continue receive datagrams.
// Important: Receive using thread pool is necessary here to avoid stack overflow with Socket.ReceiveFromAsync() method!
ThreadPool.QueueUserWorkItem(o => { ReceiveAsync(); } );
}
protected override void OnError(SocketError error)
{
Console.WriteLine($"Server caught an error with code {error}");
}
}
class Program
{
static void Main(string[] args)
{
bool help = false;
int port = 3333;
var options = new OptionSet()
{
{ "h|?|help", v => help = v != null },
{ "p|port=", v => port = int.Parse(v) }
};
try
{
options.Parse(args);
}
catch (OptionException e)
{
Console.Write("Command line error: ");
Console.WriteLine(e.Message);
Console.WriteLine("Try `--help' to get usage information.");
return;
}
if (help)
{
Console.WriteLine("Usage:");
options.WriteOptionDescriptions(Console.Out);
return;
}
Console.WriteLine($"Server port: {port}");
Console.WriteLine();
// Create a new echo server
var server = new EchoServer(IPAddress.Any, port);
server.OptionReuseAddress = true;
// Start the server
Console.Write("Server starting...");
server.Start();
Console.WriteLine("Done!");
Console.WriteLine("Press Enter to stop the server or '!' to restart the server...");
// Perform text input
for (;;)
{
string line = Console.ReadLine();
if (string.IsNullOrEmpty(line))
break;
// Restart the server
if (line == "!")
{
Console.Write("Server restarting...");
server.Restart();
Console.WriteLine("Done!");
}
}
// Stop the server
Console.Write("Server stopping...");
server.Stop();
Console.WriteLine("Done!");
}
}
}