All articles

.NET sockets: TCP framing and LAN discovery over UDP

Length-prefixed TCP frames, the Nagle algorithm and NoDelay, a Channel write queue, connect timeouts, UDP directed broadcast and error 10054 on Windows.

t.Turgay
.NET sockets: TCP framing and LAN discovery over UDP

For a LAN game or a lightweight protocol between two desktop applications, System.Net.Sockets is enough. TCP offers an ordered, reliable byte stream; UDP offers independent datagrams. This article covers message framing over TCP, the Nagle algorithm, a Channel-based write loop, connection errors and LAN discovery with UDP broadcast, with example code.

TCP is a byte stream: length-prefixed frames

TCP does not preserve message boundaries. Data sent with one Write can arrive split across several reads, or two messages can arrive in one read. Prefixing every message with a 4-byte big-endian length restores the boundaries. The reader accumulates incoming bytes and extracts a message once a complete frame is present.

The length field is untrusted data from the network: without an upper limit, one malformed packet could make the process allocate gigabytes. Negative or oversized values close the connection. If the payload is UTF-8 JSON, use a UTF8Encoding with throwOnInvalidBytes enabled so invalid bytes are not silently turned into replacement characters.

using System.Buffers.Binary;
using System.Text;

public sealed class LengthPrefixedReader
{
    public const int MaxFrame = 1 << 20;                       // 1 MiB
    private static readonly UTF8Encoding StrictUtf8 = new(false, throwOnInvalidBytes: true);
    private byte[] _buffer = new byte[4096];
    private int _count;

    public void Append(ReadOnlySpan<byte> data)
    {
        if (_count + data.Length > _buffer.Length)
            Array.Resize(ref _buffer, Math.Max(_buffer.Length * 2, _count + data.Length));
        data.CopyTo(_buffer.AsSpan(_count));
        _count += data.Length;
    }

    public bool TryRead(out string message)
    {
        message = "";
        if (_count < 4) return false;
        int length = BinaryPrimitives.ReadInt32BigEndian(_buffer);
        if (length is < 0 or > MaxFrame) throw new InvalidDataException($"Bad frame length {length}");
        if (_count < 4 + length) return false;
        message = StrictUtf8.GetString(_buffer, 4, length);
        _buffer.AsSpan(4 + length, _count - 4 - length).CopyTo(_buffer);
        _count -= 4 + length;
        return true;
    }

    public static byte[] Encode(string message)                // one buffer: prefix + payload
    {
        byte[] payload = StrictUtf8.GetBytes(message);
        if (payload.Length > MaxFrame) throw new ArgumentException("Message too large");
        byte[] frame = new byte[4 + payload.Length];
        BinaryPrimitives.WriteInt32BigEndian(frame, payload.Length);
        payload.CopyTo(frame, 4);
        return frame;
    }
}

Microsoft Learn — Use TcpClient and TcpListener

The Nagle algorithm and NoDelay

The Nagle algorithm (RFC 896) holds back new small segments while an earlier small segment is still unacknowledged, and coalesces them. It is efficient for bulk transfer, but in interactive traffic, especially combined with the receiver's delayed acknowledgements, it can add noticeable waits to small messages.

For small, latency-sensitive messages such as game commands, set Socket.NoDelay or TcpClient.NoDelay to true. Each Write may then leave as its own segment, so the length and payload must be written as one buffer; writing four bytes and then the payload needlessly produces two packets. That is why Encode in the example returns a single array.

RFC 896 — Congestion control in IP/TCP internetworks

Microsoft Learn — TcpClient.NoDelay

A read loop and a Channel write queue

NetworkStream allows one reading thread and one writing thread at the same time, but it does not support concurrent writes from several threads. Writing outgoing messages to a single-reader Channel and draining it from one loop solves that. On shutdown, call Writer.TryComplete; the loop sends what is queued and then closes the connection.

In the read loop, ReadAsync returning 0 means the peer closed the connection cleanly; that is a normal end, not an error. IOException and SocketException mean the connection dropped, InvalidDataException means a protocol violation, and OperationCanceledException means a local shutdown. Handling them separately lets the user see the right message.

using System.Net.Sockets;
using System.Threading.Channels;

public sealed class Connection
{
    private readonly TcpClient _client;
    private readonly NetworkStream _stream;
    private readonly Channel<byte[]> _outbox =
        Channel.CreateUnbounded<byte[]>(new UnboundedChannelOptions { SingleReader = true });

    public Connection(TcpClient client)
    {
        _client = client;
        _client.NoDelay = true;                     // small, latency-sensitive messages
        _stream = client.GetStream();
    }

    public bool Send(string message) => _outbox.Writer.TryWrite(LengthPrefixedReader.Encode(message));

    public void CloseAfterFlush() => _outbox.Writer.TryComplete();

    public async Task WriteLoopAsync(CancellationToken ct)
    {
        try
        {
            await foreach (byte[] frame in _outbox.Reader.ReadAllAsync(ct))
                await _stream.WriteAsync(frame, ct);
        }
        catch (Exception e) when (e is IOException or SocketException or OperationCanceledException)
        {
            // Connection lost or closed locally; the read loop reports the reason.
        }
        finally { _client.Close(); }
    }

    public async Task ReadLoopAsync(Action<string> onMessage, CancellationToken ct)
    {
        var reader = new LengthPrefixedReader();
        byte[] chunk = new byte[8192];
        int read;
        while ((read = await _stream.ReadAsync(chunk, ct)) > 0)   // 0: peer closed
        {
            reader.Append(chunk.AsSpan(0, read));
            while (reader.TryRead(out string message)) onMessage(message);
        }
    }
}

Microsoft Learn — System.Threading.Channels

Connect timeouts, port 0 and the firewall

TcpClient.ConnectAsync can be cancelled through its CancellationToken overload; CancellationTokenSource.CancelAfter sets a limit of a few seconds. For an unreachable address, the operating system's default wait is far too long for a user. Classify errors when showing them: connection refused (nobody listening), timeout and name resolution failure each need a different fix.

In tests, or when running several instances on one machine, bind the listener to port 0; the operating system picks a free port and the actual value is read from LocalEndpoint. Listen on IPAddress.Loopback for local experiments and on IPAddress.Any for other machines on the network. In the second case, Windows Firewall may ask the user for permission on first listen, so document that step in the setup notes.

Microsoft Learn — TcpClient.ConnectAsync

LAN discovery with UDP broadcast

The machine hosting a game broadcasts a small UDP announcement every few seconds: a fixed magic prefix, the protocol version, the game name and the TCP port. Listening clients keep announcements in a list and drop entries that have not been refreshed for a while. Packet size is capped, packets without the prefix are skipped, and numbers are parsed with CultureInfo.InvariantCulture.

On machines with several interfaces, the limited broadcast address 255.255.255.255 may leave through only one of them. Computing a directed broadcast address for each IPv4 interface, the address ORed with the inverted mask, reaches every local network. Enable ReuseAddress before binding so several clients on one machine can listen on the same port; the sender needs EnableBroadcast.

using System.Buffers.Binary;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;

public static IEnumerable<IPAddress> BroadcastTargets()
{
    foreach (var nic in NetworkInterface.GetAllNetworkInterfaces())
    {
        if (nic.OperationalStatus != OperationalStatus.Up ||
            nic.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue;

        foreach (var unicast in nic.GetIPProperties().UnicastAddresses)
        {
            if (unicast.Address.AddressFamily != AddressFamily.InterNetwork) continue;
            if (unicast.IPv4Mask is null || unicast.IPv4Mask.Equals(IPAddress.Any)) continue;
            uint ip = BinaryPrimitives.ReadUInt32BigEndian(unicast.Address.GetAddressBytes());
            uint mask = BinaryPrimitives.ReadUInt32BigEndian(unicast.IPv4Mask.GetAddressBytes());
            var bytes = new byte[4];
            BinaryPrimitives.WriteUInt32BigEndian(bytes, ip | ~mask);
            yield return new IPAddress(bytes);
        }
    }
}

public static UdpClient CreateListener(int port = 47777)
{
    var udp = new UdpClient { ExclusiveAddressUse = false };
    udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
    udp.Client.Bind(new IPEndPoint(IPAddress.Any, port));
    return udp;
}

// Sender: using var udp = new UdpClient { EnableBroadcast = true };
//         foreach (var target in BroadcastTargets())
//             await udp.SendAsync(packet, new IPEndPoint(target, 47777));

Microsoft Learn — UdpClient

Error 10054 on Windows and monotonic time

On Windows, if a packet sent from a UDP socket triggers an ICMP "port unreachable" reply, the next receive on the same socket can fail with WSAECONNRESET (10054). UDP is connectionless, so this must not stop the listener: catch SocketError.ConnectionReset and continue the loop, or turn the behaviour off with the SIO_UDP_CONNRESET control code.

Measure announcement lifetimes with Stopwatch rather than DateTime.Now; the wall clock can move backwards with daylight saving changes, manual adjustment or time synchronization, while Stopwatch.GetTimestamp increases monotonically. The listening thread and the UI touch the announcement list at the same time, so protect access with a lock and give the UI a copy of the list.

Microsoft Learn — Windows Sockets error codes

Related technical articles

You have reached the end of this orbit.
Explore more articles
turgay.A little code, a few pixels, a lot of curiosity.© 2026 · Made on Earth