NTDLS.DatagramMessaging Usage
Sending and receiving serialized UDP packets with fragmentation, compression and encryption handled for you.
NTDLS.DatagramMessaging
What it is. A set of classes and extension methods that make sending and receiving UDP packets in C# painless. It handles corruption checks, concatenation, fragmentation, serialization, compression and encryption, so your code works with objects instead of raw byte arrays.
When to reach for it. You want reliable object-level messaging over UDP - game state sync, sensor telemetry, lightweight client-server chatter - without hand-rolling packet framing or worrying about messages larger than a single datagram. Skip it if you need guaranteed delivery or ordering; UDP is still best-effort underneath, and for that you want TCP (see NTDLS.ReliableMessaging).
Getting started
Any message class simply implements IDmDatagram:
public class MyFirstUDPPacket : IDmDatagram
{
public DateTime TimeStamp { get; set; } = DateTime.UtcNow;
public Guid UID { get; set; } = Guid.NewGuid();
public string Message { get; set; } = string.Empty;
public MyFirstUDPPacket() { }
public MyFirstUDPPacket(string message)
{
Message = message;
}
}
A server listens on a port and reacts to incoming datagrams through the OnDatagramReceived event:
static void Main()
{
using var messenger = new DmMessenger(1234);
messenger.OnDatagramReceived += Messenger_OnDatagramReceived;
Console.WriteLine("Press enter to quit.");
Console.ReadLine();
}
private static void Messenger_OnDatagramReceived(DmContext context, IDmDatagram datagram)
{
if (datagram is MyFirstUDPPacket packet)
{
// Echo the datagram back to the sender.
context.Dispatch(packet);
Console.WriteLine($"{packet.Message} -> {packet.UID}");
}
}
A client is just a DmMessenger with no listen port (write-only mode). GetEndpointContext resolves the destination, and Dispatch serializes and sends:
using var messenger = new DmMessenger();
var endpointCtx = messenger.GetEndpointContext("127.0.0.1", 1234);
for (int i = 0; i < 10; i++)
{
messenger.Dispatch(new MyFirstUDPPacket($"Packet #{i}"), endpointCtx);
Thread.Sleep(10);
}
If you prefer convention-based handling, implement IDmMessageHandler with a method whose signature matches your datagram type, and register it with AddHandler() instead of hooking the event.
NuGet: NTDLS.DatagramMessaging