Skip to content

Instantly share code, notes, and snippets.

@guitarrapc
Created October 7, 2022 06:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guitarrapc/dcf6bd59c9fe39d149d854a6aa8fcdda to your computer and use it in GitHub Desktop.
Save guitarrapc/dcf6bd59c9fe39d149d854a6aa8fcdda to your computer and use it in GitHub Desktop.
C# UDP Server and Client sample
async Task Main()
{
using var cts = new CancellationTokenSource();
var host = "127.0.0.1";
var port = 8125;
using var client = new Client(host, port);
using var server = new UdpServer(host, port)
{
OnRecieveMessage = (endpoint, text) =>
{
Console.WriteLine($"{endpoint.Address}:{endpoint.Port}: {text}");
}
};
var serverTask = Task.Run(async () => await server.ListenAsync(cts.Token), cts.Token);
var i = 0;
while (i < 10)
{
await client.SendAsync("hello");
await Task.Delay(100);
i++;
}
cts.Cancel();
}
public class UdpServer : IDisposable
{
private UdpClient _udp;
public Action<IPEndPoint, string>? OnRecieveMessage {get; set;}
public UdpServer(string host, int port)
{
var endpoint = new System.Net.IPEndPoint(IPAddress.Parse(host), port);
_udp = new UdpClient(endpoint);
}
public void Dispose()
{
_udp.Dispose();
}
public async ValueTask ListenAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
var result = await _udp.ReceiveAsync(ct);
OnRecieveMessage?.Invoke(result.RemoteEndPoint, Encoding.UTF8.GetString(result.Buffer));
}
}
}
public class Client : IDisposable
{
private UdpClient _udp;
private IPEndPoint _endpoint;
public Client(string host, int port)
{
_endpoint = new System.Net.IPEndPoint(IPAddress.Parse(host), port);
_udp = new UdpClient();
}
public async ValueTask SendAsync(string message)
{
var bytes = Encoding.UTF8.GetBytes(message);
await _udp.SendAsync(bytes, bytes.Length, _endpoint);
}
public void Dispose()
{
_udp.Dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment