-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathProgram.cs
More file actions
174 lines (147 loc) · 5.09 KB
/
Program.cs
File metadata and controls
174 lines (147 loc) · 5.09 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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// This program was designed for test purposes only
/// Not for a review
/// </summary>
namespace NetSdrClientApp.EchoServer
{
public class EchoServer
{
private readonly int _port;
private TcpListener _listener;
private readonly CancellationTokenSource _cancellationTokenSource;
public EchoServer(int port)
{
_port = port;
_cancellationTokenSource = new CancellationTokenSource();
}
public async Task StartAsync()
{
_listener = new TcpListener(IPAddress.Any, _port);
_listener.Start();
Console.WriteLine($"Server started on port {_port}.");
while (!_cancellationTokenSource.Token.IsCancellationRequested)
{
try
{
TcpClient client = await _listener.AcceptTcpClientAsync();
Console.WriteLine("Client connected.");
_ = Task.Run(() => HandleClientAsync(client, _cancellationTokenSource.Token));
}
catch (ObjectDisposedException)
{
// Listener has been closed
break;
}
}
Console.WriteLine("Server shutdown.");
}
private async Task HandleClientAsync(TcpClient client, CancellationToken token)
{
using (NetworkStream stream = client.GetStream())
{
try
{
byte[] buffer = new byte[8192];
int bytesRead;
while (!token.IsCancellationRequested &&
(bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, token)) > 0)
{
await stream.WriteAsync(buffer, 0, bytesRead, token);
Console.WriteLine($"Echoed {bytesRead} bytes to the client.");
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
client.Close();
Console.WriteLine("Client disconnected.");
}
}
}
public void Stop()
{
_cancellationTokenSource.Cancel();
_listener.Stop();
_cancellationTokenSource.Dispose();
Console.WriteLine("Server stopped.");
}
public static async Task Main(string[] args)
{
EchoServer server = new EchoServer(5000);
_ = Task.Run(() => server.StartAsync());
string host = "127.0.0.1";
int port = 60000;
int intervalMilliseconds = 5000;
using var sender = new UdpTimedSender(host, port);
Console.WriteLine("Press any key to stop sending...");
sender.StartSending(intervalMilliseconds);
Console.WriteLine("Press 'q' to quit...");
while (Console.ReadKey(intercept: true).Key != ConsoleKey.Q)
{
}
sender.StopSending();
server.Stop();
Console.WriteLine("Sender stopped.");
}
}
public class UdpTimedSender : IDisposable
{
private readonly string _host;
private readonly int _port;
private readonly UdpClient _udpClient;
private Timer? _timer;
private ushort _counter;
public UdpTimedSender(string host, int port)
{
_host = host;
_port = port;
_udpClient = new UdpClient();
}
public void StartSending(int intervalMilliseconds)
{
if (_timer != null)
throw new InvalidOperationException("Sender is already running.");
_timer = new Timer(SendMessageCallback, null, 0, intervalMilliseconds);
}
private void SendMessageCallback(object? state)
{
try
{
var rnd = new Random();
byte[] samples = new byte[1024];
rnd.NextBytes(samples);
_counter++;
byte[] msg = new byte[] { 0x04, 0x84 }
.Concat(BitConverter.GetBytes(_counter))
.Concat(samples)
.ToArray();
var endpoint = new IPEndPoint(IPAddress.Parse(_host), _port);
_udpClient.Send(msg, msg.Length, endpoint);
Console.WriteLine($"Message sent to {_host}:{_port} ");
}
catch (Exception ex)
{
Console.WriteLine($"Error sending message: {ex.Message}");
}
}
public void StopSending()
{
_timer?.Dispose();
_timer = null;
}
public void Dispose()
{
StopSending();
_udpClient.Dispose();
}
}
}