Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson2 / 15

    TCP vs UDP for .NET Developers: Sockets, Handshakes, Framing and TIME_WAIT

    TCP provides a reliable, ordered byte stream; UDP sends separate messages without delivery guarantees. In .NET you work with TCP and UDP through sockets. To use them safely, you need message framing and an understanding of connection states such as TIME_WAIT.

    You will learn why one TCP read may not contain a whole message, what TIME_WAIT means, and why an idle connection can still fail. For a refresher on addresses and ports, start with how a request crosses the network.

    TCP vs UDP: which should you choose?

    TCP, or Transmission Control Protocol, gives applications an ordered stream of bytes. It tracks missing data and retransmits it. A connection that cannot recover eventually reports failure rather than guaranteeing delivery forever.

    UDP, or User Datagram Protocol, sends individual messages called datagrams. It preserves their boundaries, but does not guarantee arrival or arrival order.

    In .NET, UdpClient provides SendAsync and ReceiveAsync. Each successful ReceiveAsync returns one datagram, rather than an arbitrary part of a byte stream.

    BehaviourTCPUDP
    Connection setupEstablishes a connection before ordinary data exchangeNo TCP-style connection handshake
    DeliveryRetransmits missing data, or reports failureNo built-in delivery guarantee
    OrderingDelivers bytes in orderDatagrams may arrive out of order
    Message boundariesDoes not preserve application writesPreserves datagram boundaries
    Traffic controlBuilt-in flow and congestion control, explained belowNeither is supplied by UDP itself

    Choose TCP when complete, ordered data matters. Choose UDP when late data is useless, as with some live media and game updates, or when another protocol supplies reliability.

    DNS, which translates names into information such as IP addresses, commonly uses UDP but can also use TCP. QUIC is another UDP-based protocol; we will see why that does not make it unreliable.

    The mistake to avoid. UDP is not simply “faster TCP.” Removing TCP's guarantees means accepting their absence or implementing the behaviour your application needs.

    In an interview, say: “TCP provides a reliable, ordered byte stream with flow and congestion control. UDP preserves datagrams but guarantees neither delivery nor order. I would choose UDP when late data is useless, or when a higher protocol supplies reliability, as QUIC does.”

    What is a socket, and why does TCP use a three-way handshake?

    A socket is the operating system's endpoint for one side of the communication. It is not itself a protocol: .NET's Socket class can work with TCP or UDP.

    For TCP, TcpClient and TcpListener provide simpler APIs over sockets. TcpListener listens for connections; accepting one creates a separate object for communicating with that client. TcpClient.GetStream() exposes the connection as a NetworkStream.

    Microsoft's TcpClient and TcpListener guide explains these helpers. Use Socket directly when you need lower-level control.

    Before ordinary data exchange, TCP performs a handshake: messages that establish the connection's shared state. TCP numbers bytes so it can track their order and acknowledge receipt. Each direction starts with an initial sequence number.

    sequenceDiagram
        participant C as Client
        participant S as Server
        C->>S: SYN: propose initial number
        S->>C: SYN-ACK: acknowledge and propose
        C->>S: ACK: acknowledge server number

    SYN means synchronize, and ACK means acknowledgment. The final ACK confirms that the initiator received the server's response. This helps reject stale connection attempts rather than treating an old request as a new connection.

    Ordinary TCP setup costs about one round trip (RTT) before the initiator can send application data.

    The mistake to avoid. The handshake does not prove that an application request succeeded. It establishes TCP state, not the result of your business operation.

    In an interview, say: “TCP uses SYN, SYN-ACK and ACK to establish connection state and acknowledge both initial sequence numbers. The final ACK confirms the initiator received the response, helping reject stale attempts. Ordinary setup costs about one RTT.”

    TCP flow control, congestion control and Nagle's algorithm

    Flow control prevents a sender from overrunning the receiver's available buffering. The receiver advertises a receive window: how much additional data it is currently prepared to accept.

    Congestion control limits sending according to conditions along the network path. It protects the network, not just the receiving application.

    For example, a receiver may have plenty of buffer space while an intermediate network link is overloaded. A large receive window does not remove that network bottleneck.

    Slow start is a congestion-control phase that begins with a limited amount of data sent but not yet acknowledged and increases it as acknowledgments arrive. It can hold back a fresh connection, which is one more reason to reuse connections.

    Nagle's algorithm reduces small TCP transmissions by holding some small writes while earlier data remains unacknowledged. This can improve efficiency but add latency to small, interactive exchanges.

    Receivers may briefly delay acknowledgments, a behaviour called delayed ACK. Together with Nagle, this can hold back a small second write until the acknowledgment arrives. This matters when a receiver needs both writes before it can respond.

    In .NET, TcpClient.NoDelay defaults to false, leaving Nagle enabled; setting it to true disables the algorithm. HttpClient and Kestrel already turn Nagle off: SocketsHttpHandler creates its sockets with NoDelay = true (unless you supply your own ConnectCallback), and Kestrel's SocketTransportOptions.NoDelay defaults to true. NoDelay does not turn writes into messages or guarantee immediate delivery. See the NoDelay documentation.

    The mistake to avoid. Do not treat every delay as receiver slowness, or disable Nagle as a universal performance fix. The receiver, network and write pattern impose different limits.

    In an interview, say: “Flow control protects receiver buffers; congestion control adjusts sending to network conditions, and slow start limits a new connection. Nagle combines small writes while earlier data is unacknowledged, and with delayed ACK it can add latency. TcpClient leaves it on; HttpClient and Kestrel turn it off. For small latency-sensitive messages on my own sockets, I would set NoDelay, also called TCP_NODELAY.”

    Why can one TCP read return half a message?

    TCP preserves byte order, not write boundaries. Two writes containing HE and LLO might be read as HELLO, HE then LLO, or other groupings. Separate application messages can also appear in one read.

    Predict this program's two lines. It uses an in-memory stream, not a live socket, to make two possible read groupings repeatable.

    C#Runs
    using System.Text;
    
    using var stream = new MemoryStream();
    await stream.WriteAsync(Encoding.ASCII.GetBytes("HE"));
    await stream.WriteAsync(Encoding.ASCII.GetBytes("LLO"));
    
    foreach (int bufferSize in new[] { 3, 5 })
    {
        stream.Position = 0;
        var buffer = new byte[bufferSize];
        var pieces = new List<string>();
        int count;
        while ((count = await stream.ReadAsync(buffer.AsMemory())) != 0)
        {
            pieces.Add(Encoding.ASCII.GetString(buffer, 0, count));
        }
        Console.WriteLine($"Buffer {bufferSize}: {string.Join(" | ", pieces)}");
    }
    Output
    Buffer 3: HEL | LO
    Buffer 5: HELLO

    Both passes read the same five bytes. Neither reconstructs the original write boundaries automatically.

    A real TCP read can return fewer bytes than its buffer holds, even over loopback (traffic to the same computer).

    You need framing: an application rule that identifies where each message starts and ends. Two common rules are a length prefix and a delimiter.

    The mistake to avoid. A large buffer does not turn one read into “read one message.” Its size limits how much you can receive in that call, not where a message ends.

    In an interview, say: “TCP preserves byte order, not write boundaries. Reads can split one message or combine several. The application needs framing, such as a length prefix or delimiter, and must keep reading until that frame is complete.”

    How do you read a length-prefixed TCP message safely?

    A length prefix places the message's byte count before its contents. Here, our format uses four bytes for the count, followed by that many content bytes.

    Both endpoints must agree on byte order. This example uses big-endian order: the most significant byte comes first. It also limits content to 1,024 bytes.

    EOF, or end of stream, means no more bytes are available from that stream. For a non-empty NetworkStream read, a result of zero indicates the other endpoint (the peer) has gracefully ended its sending direction.

    Our reader distinguishes two situations:

    • EOF before the first prefix byte means there is no next frame.
    • EOF after a frame has started means the frame was cut short, or truncated.

    ReadExactlyAsync fills a known-length buffer or throws EndOfStreamException if EOF arrives first.

    Predict which cases below succeed. The test stream deliberately returns at most two bytes per read, so a successful frame requires multiple reads. No network access is needed.

    C#Runs
    using System.Buffers.Binary;
    using System.Text;
    
    var cases = new (string Name, byte[] Data)[]
    {
        ("Complete", new byte[] { 0, 0, 0, 5, 72, 69, 76, 76, 79 }),
        ("Clean EOF", Array.Empty<byte>()),
        ("Short header", new byte[] { 0, 0 }),
        ("Short body", new byte[] { 0, 0, 0, 5, 72, 69 }),
        ("Oversized", new byte[] { 0, 0, 8, 0 }),
        ("Negative", new byte[] { 255, 255, 255, 255 })
    };
    
    foreach (var item in cases)
    {
        using var stream = new SmallReadStream(item.Data);
        try
        {
            byte[]? payload = await ReadFrameAsync(stream);
            Console.WriteLine($"{item.Name}: " +
                (payload is null ? "no next frame" : Encoding.ASCII.GetString(payload)));
        }
        catch (EndOfStreamException)
        {
            Console.WriteLine($"{item.Name}: truncated frame");
        }
        catch (InvalidDataException)
        {
            Console.WriteLine($"{item.Name}: invalid length");
        }
    }
    
    static async Task<byte[]?> ReadFrameAsync(
        Stream stream, CancellationToken cancellationToken = default)
    {
        const int MaxPayloadLength = 1024;
        var header = new byte[4];
    
        int first = await stream.ReadAsync(header.AsMemory(0, 1), cancellationToken);
        if (first == 0)
            return null;
    
        await stream.ReadExactlyAsync(header.AsMemory(1), cancellationToken);
        int length = BinaryPrimitives.ReadInt32BigEndian(header);
        if (length < 0 || length > MaxPayloadLength)
            throw new InvalidDataException("Invalid frame length.");
    
        var payload = new byte[length];
        await stream.ReadExactlyAsync(payload.AsMemory(), cancellationToken);
        return payload;
    }
    
    sealed class SmallReadStream(byte[] data) : MemoryStream(data)
    {
        public override ValueTask<int> ReadAsync(
            Memory<byte> buffer, CancellationToken cancellationToken = default)
        {
            return base.ReadAsync(buffer[..Math.Min(buffer.Length, 2)], cancellationToken);
        }
    }
    Output
    Complete: HELLO
    Clean EOF: no next frame
    Short header: truncated frame
    Short body: truncated frame
    Oversized: invalid length
    Negative: invalid length

    The first read asks for one byte, because only there can zero mean a clean end between frames. The reader checks the decoded length before allocating the content buffer.

    A delimiter is an agreed marker, such as a newline, that ends a message. With delimiter framing, retain unfinished bytes between reads and process every complete message already buffered. Decide what happens if the message itself contains a newline, for example escape it. Stop with an error if no delimiter appears within the size limit. If the stream ends in the middle of a message, treat it as truncated.

    The mistake to avoid. Do not trust a received length or treat every EOF as a clean close. An unchecked length can cause excessive allocation; EOF inside a frame means missing data.

    In an interview, say: “I define framing and validate lengths before allocation. ReadExactlyAsync fills a known length or throws at premature EOF. EOF before a new frame can be clean; EOF inside its header or body is truncation. Delimiter framing also needs buffering and a size limit.”

    What do TIME_WAIT and CLOSE_WAIT mean?

    TCP can close its two sending directions separately. A FIN signals that an endpoint has no more bytes to send. The peer acknowledges it, but may still send its own remaining data.

    sequenceDiagram
        participant A as Active closer
        participant B as Peer
        A->>B: FIN: finished sending
        B->>A: ACK
        Note over B: CLOSE_WAIT until local close
        B->>A: FIN: finished sending
        A->>B: ACK
        Note over A: TIME_WAIT

    The active closer is the endpoint that initiates closure. It normally enters TIME_WAIT after acknowledging the peer's FIN.

    TIME_WAIT lasts 2 × MSL. MSL means maximum segment lifetime: the lifetime assumed for an old TCP segment, a unit of TCP data travelling over the network. Waiting protects a later connection from delayed old segments and allows the final ACK to be sent again if the peer retransmits its FIN.

    TIME_WAIT is normal. Large counts suggest connection churn: repeatedly creating and closing connections. Linux commonly uses about 60 seconds; Windows timing is configurable. Do not quote one duration as universal.

    CLOSE_WAIT means the peer's FIN arrived, but the local sending direction remains open. A persistent, unexplained accumulation usually points to delayed or missing local cleanup. Check who owns and disposes sockets, clients, streams and HTTP responses. A temporary or intentional half-close, where only one sending direction has ended, is not necessarily a leak.

    Microsoft's TCP/IP port exhaustion guide discusses these symptoms. Port exhaustion means insufficient available local ports for new outbound connections; a high state count alone does not prove it.

    The mistake to avoid. Do not diagnose TIME_WAIT as a resource leak, or assume CLOSE_WAIT will disappear through the same waiting period. They describe different stages and ownership responsibilities.

    In an interview, say: “Normally the active closer enters TIME_WAIT for twice MSL, protecting against old segments and allowing the final ACK to be resent. It is normal; high counts suggest churn. Persistent CLOSE_WAIT means the peer closed its sending side while local cleanup remains unfinished.”

    HTTP keep-alive vs TCP keep-alive: why can idle connections fail?

    HTTP keep-alive means reusing a connection for more requests rather than creating one per request. A connection pool holds reusable connections for later operations.

    TCP keep-alive is a separate, optional mechanism that sends probes during inactivity to detect an unresponsive peer. It does not check whether an HTTP operation is making useful progress; see SO_KEEPALIVE.

    A load balancer distributes traffic among servers and may track each connection. Its idle timeout limits how long it retains an inactive connection's state.

    For example, Azure Load Balancer documents a default idle timeout of four minutes. A connection can expire there before an operating system's default TCP keep-alive probes begin. With reset notifications disabled, traffic may be silently dropped. A TCP reset, or RST, instead aborts the connection and notifies a receiving endpoint.

    Consequently, a pooled connection that worked earlier can fail on its next use. Keep operation timeouts even when reuse or probes are enabled. The Azure idle timeout documentation explains the configuration trade-off.

    The mistake to avoid. Neither keeping an object in a pool nor enabling probes guarantees that its next operation will succeed.

    In an interview, say: “HTTP keep-alive reuses connections for more requests. TCP keep-alive sends optional idle probes to detect an unresponsive peer. Neither replaces operation timeouts, and a load balancer can expire an idle connection before default probes begin.”

    Why does QUIC use UDP if UDP is unreliable?

    QUIC, the transport under HTTP/3, runs over UDP because almost every network and operating system already passes UDP, and QUIC can then provide reliable, ordered streams itself. Losing data on one stream does not stall the others, unlike TCP. UDP can be blocked, so QUIC is not automatically usable or faster; HTTP/1.1 vs HTTP/2 vs HTTP/3 covers the rest.

    Check yourself

    A TCP sender writes a four-byte length prefix and then a 200-byte body. What must the receiver assume?

    A The first read can be relied on for the four-byte prefix, as TCP keeps each write as one segment.
    B A 204-byte receive buffer gets the whole frame in one read, as both writes arrive together.
    C Reads may split or combine the writes, so the receiver must assemble the frame.
    D No framing is needed, because TCP's reliable delivery preserves each message's boundaries.
    Show answer

    Correct answer: C

    TCP preserves byte order, not write boundaries. Read the complete prefix, validate its length, and then read the complete body. EOF inside either part means truncation.

    A service has a growing number of CLOSE_WAIT connections that never disappear. What should you investigate first?

    A Whether local code fails to finish and clean up connections after the peer sends FIN.
    B Whether the operating system's TIME_WAIT timer is set too long for this traffic.
    C Whether the remote peer is failing to send its FIN after the request completes.
    D Whether the receive buffers are too small, so unread data is holding the connections open.
    Show answer

    Correct answer: A

    CLOSE_WAIT means the peer ended its sending direction while the local sending direction remains open. Persistent unexplained accumulation suggests a local ownership or cleanup problem, not normal TIME_WAIT protection.

    Going deeper

    When using Socket.SendAsync directly, check its returned byte count and continue until all intended bytes have been sent. A successful send also does not prove that the receiving application processed the data.

    For text protocols, agree on an encoding, such as UTF-8, which represents characters as bytes. A character may span reads, so avoid decoding each arbitrary read independently.

    For larger parsers, System.IO.Pipelines manages the buffering for you; you still enforce message limits and reject incomplete frames at EOF.

    For the practical .NET consequences of frequent closes and unclear response ownership, continue with connection pooling and socket exhaustion.

    Sources

    Practice

    Practice test: Practice: TCP vs UDP for .NET Developers: Sockets, Handshakes, Framing and TIME_WAIT9 questions · 1 mark each, no negative markingFull Access
    Take the test
    Sign in to mark lessons done and keep your place in the course.Sign in

    Checked before publishing: C# examples run on .NET 10, links opened, reviewed while it was written and read in full. How lessons are checked

    Updated 30 Nov 2026 ·