Skip to content
Tutorials Center
My learning

Topics

Lesson 124 of 182 ยท Standard Library

TCP, UDP and Named Pipes

Learn network programming in C#: build a TCP echo server with TcpListener and TcpClient, send UDP datagrams, use raw Socket, and talk between processes with named pipes.

HTTP is built on top of simpler things. Underneath it, computers exchange bytes over TCP connections or UDP datagrams, and programs on the same machine can talk through pipes. Knowing these building blocks helps you understand how HttpClient works, lets you write your own protocols (chat servers, game servers, device controllers, a quick health-check port), and gives you a fast way to connect two processes without any web server.

This lesson covers TcpListener and TcpClient, a line-based protocol on top of them, UDP with UdpClient, the low-level Socket class, and named pipes for inter-process communication (IPC). Every demo runs the server and the client inside the same program, using the loopback address 127.0.0.1, so it works without a network. Make sure you know async and await, streams and tasks.

TCP versus UDP

flowchart LR
    subgraph TCP["TCP: connection, ordered stream"]
      direction LR
      C1["Client"] -->|"connect, then bytes in order"| S1["Server"]
    end
    subgraph UDP["UDP: separate datagrams"]
      direction LR
      C2["Sender"] -.->|"packet, may be lost or reordered"| S2["Receiver"]
    end

TCP gives you a reliable ordered byte stream; UDP gives you independent packets without guarantees.

TCP UDP
Connection Yes (handshake first) No
Delivery Reliable, ordered, no duplicates Best effort: loss, reordering possible
Data model A stream of bytes, no message boundaries Messages (datagrams) with boundaries
Typical use HTTP, databases, SSH, chat DNS, voice/video, games, discovery

The key mental shift for TCP: it is a stream. If you send "HELLO" and "WORLD" in two writes, the receiver may read "HELLOWORLD" in one read, or "HEL" and "LOWORLD" in two. TCP does not keep your message boundaries. Protocols therefore need their own framing: a line ending, a length prefix, or a fixed size.

A TCP echo server and client

TcpListener waits for incoming connections on a port. AcceptTcpClientAsync returns a TcpClient for each connection. Both sides get a NetworkStream, which behaves like any other stream. Wrapping it in a StreamReader and StreamWriter lets us use lines of text as the framing.

C# An echo server in one program

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Several details matter here:

  • Port 0 asks the operating system for any free port, and LocalEndpoint tells us which one. It is the best way to avoid "address already in use" errors in tests and demos.
  • AutoFlush = true sends each line right away. Without it the writer buffers, both sides wait for each other and the program hangs.
  • ReadLineAsync returns null when the other side closes the connection. That is how a server notices that a client left.
  • IPAddress.Loopback (127.0.0.1) accepts connections only from the same machine. IPAddress.Any would listen on all network cards, which exposes the server to your network. Choose deliberately.

Serving many clients

A real server does not stop after one client. It runs an accept loop and starts a task for each connection, so a slow client never blocks others. Here we accept three clients at the same time and keep a safe counter.

C# One task per connection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The same pattern scales to thousands of clients because the awaits free up threads (see task combinators). Production servers add timeouts, cancellation tokens (cancellation), a maximum line length so a malicious client cannot send an endless line, and error handling around every connection.

Framing: where does a message end?

Line endings are fine for text protocols. For binary data, the usual technique is a length prefix: four bytes for the length, followed by that many bytes of payload. The reader first reads exactly four bytes, then exactly that many more. Stream.ReadExactlyAsync (.NET 7+) loops until all requested bytes arrived, which is crucial because a single ReadAsync may return fewer bytes than you asked for.

C# Length-prefixed messages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice the byte order: network protocols conventionally use big endian ("network byte order"), which is why we use BinaryPrimitives.*BigEndian. Always validate the length before allocating, otherwise a client claiming a 2 GB message can exhaust your memory.

UDP datagrams

With UDP there is no connection. Each SendAsync produces one datagram, and each ReceiveAsync returns one whole datagram, including the sender's address, so message boundaries are preserved. Loopback UDP almost never loses packets, but on a real network it can, so never rely on delivery without your own acknowledgements.

C# UDP on the loopback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Each datagram arrives as its own message, with its own length. That is the opposite of TCP's stream behavior. UDP also supports broadcast and multicast, which is how many "discover devices on my network" features work. A datagram larger than the network's MTU (about 1,400 safe bytes) is split into fragments and one lost fragment loses the whole datagram, so keep payloads small.

The Socket class

TcpClient, TcpListener and UdpClient are friendly wrappers around System.Net.Sockets.Socket. When you need control over options (buffer sizes, keep-alive, NoDelay, IPv6 dual-mode, Unix domain sockets), use Socket directly. The calls mirror the classic BSD socket API: create, bind, listen, accept, connect, send, receive.

C# Using Socket directly

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

This tiny exchange works only because both messages are short and arrive in one piece. In real code you would loop and frame the data as shown above. Sockets also give you Shutdown(SocketShutdown.Send), which tells the peer that you are finished sending while you can still receive.

Named pipes: talking between processes

Sometimes two programs on the same machine need to talk: a background service and a tray app, a build tool and its worker processes, or a launcher and a game. A named pipe is a channel identified by a name instead of a port. It is faster than TCP loopback, never exposed to the network, and on Windows can be secured with ACLs. In .NET you use NamedPipeServerStream and NamedPipeClientStream from System.IO.Pipes. They are ordinary streams, so StreamReader and StreamWriter work as usual.

On Linux and macOS, .NET implements named pipes with Unix domain sockets in a temp folder, so the same code runs on every platform.

C# A named pipe between two tasks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The server creates the pipe and waits. The client connects by name; "." stands for the local computer (pipes can also cross the network on Windows, with a machine name instead). The name must be unique, which is why we add the process id. Remember that each NamedPipeServerStream serves one client at a time. To serve several clients, create a new server instance in a loop (the constructor's maxNumberOfServerInstances parameter allows multiple instances of the same name). For one-way messaging, use PipeDirection.In on one side and Out on the other. There are also anonymous pipes (AnonymousPipeServerStream), which connect a parent process to a child it starts, without any name.

Choosing the right tool

Need Use
Call a web API HttpClient (HttpClient lesson)
Custom reliable protocol over the network TcpListener / TcpClient
Fire-and-forget packets, discovery, telemetry UdpClient
Special socket options, Unix domain sockets Socket
Two processes on one machine Named pipes
Many consumers, durable messages A message broker, not raw sockets

Safety checklist

  • Bind to IPAddress.Loopback unless the server must be reachable from other machines.
  • Set read/write timeouts or use cancellation tokens; a client that connects and sends nothing must not hold a task forever.
  • Limit message sizes before allocating buffers.
  • Treat every byte from the network as untrusted input and validate it.
  • Use TLS (SslStream) when data leaves the machine. Plain TCP is readable by anyone on the path.
  • Always dispose clients, listeners and streams.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You send 'HELLO' and then 'WORLD' over a TCP connection in two writes. What can the receiver observe?

    TCP delivers an ordered stream of bytes. Write boundaries are not preserved, so protocols add framing such as line endings or length prefixes.
  2. 2. Why use port 0 when you create a TcpListener in a test or demo?

    Binding to port 0 asks the OS for any available port. Read it from LocalEndpoint afterwards and pass it to the client.
  3. 3. What does StreamReader.ReadLineAsync return when the remote side closes the TCP connection?

    A null result means the end of the stream. Server loops use it to stop reading from a client that disconnected.
  4. 4. How does UDP differ from TCP in handling messages?

    UDP is connectionless: each send is one datagram that arrives whole (or not at all), possibly out of order. TCP provides reliability and ordering but no message boundaries.
  5. 5. When are named pipes the better choice than TCP sockets?

    Named pipes are local IPC. They are not exposed to the network by default and have less overhead than loopback TCP. For remote communication use TCP (with TLS).

Summary

  • TCP (TcpListener, TcpClient) gives a reliable ordered byte stream; you add framing with lines or length prefixes.
  • Use one task per connection, ReadExactlyAsync for fixed-size reads, and port 0 plus LocalEndpoint in tests.
  • UDP (UdpClient) sends independent datagrams that can be lost or reordered.
  • Socket is the low-level class behind them all for advanced options.
  • Named pipes (NamedPipeServerStream, NamedPipeClientStream) connect processes on one machine.
  • Bind to loopback by default, limit sizes, add timeouts, validate input and use TLS across networks.

Next lesson: Zip and GZip compression.