C# Reference ยท Files and I/O
Sockets: TcpListener, TcpClient and Socket
Reference for TCP sockets in C#: TcpListener, TcpClient, NetworkStream and Socket, building an echo server, message framing, timeouts and disposal.
Sockets are the lowest-level network API in .NET. For TCP, two convenience classes cover most needs: TcpListener waits for incoming connections on an address and port, and TcpClient connects to a server. Once connected, both sides get a NetworkStream, an ordinary Stream you can read and write with StreamReader, StreamWriter, BinaryReader or raw byte buffers. System.Net.Sockets.Socket is the class underneath, with full control over socket options, UDP, and other protocols.
TCP is a byte stream, not a message protocol. One Write on one side can arrive as several Read results on the other, and several writes can be merged into one read. You must define your own framing: a delimiter such as a newline, a length prefix, or a fixed size. Most beginner bugs with sockets come from forgetting this.
var listener = new TcpListener(IPAddress.Loopback, 0); // port 0: any free port listener.Start(); int port = ((IPEndPoint)listener.LocalEndpoint).Port;
Try it
Only loopback (127.0.0.1) connections work in this site's runner, so the server and the client run in the same 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.
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.
Syntax
public TcpListener(IPAddress localaddr, int port); public void Start(); public void Stop(); public Task<TcpClient> AcceptTcpClientAsync(CancellationToken cancellationToken = default); public Task<Socket> AcceptSocketAsync(); public EndPoint LocalEndpoint { get; } public TcpClient(); public Task ConnectAsync(IPAddress address, int port); public Task ConnectAsync(string host, int port); public NetworkStream GetStream(); public bool Connected { get; } public int ReceiveTimeout { get; set; } public bool NoDelay { get; set; } public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType); public void Bind(EndPoint localEP); public void Listen(int backlog); public ValueTask<int> ReceiveAsync(Memory<byte> buffer, SocketFlags flags); public ValueTask<int> SendAsync(ReadOnlyMemory<byte> buffer, SocketFlags flags); public void Shutdown(SocketShutdown how);
| Name | Description |
|---|---|
IPAddress |
IPAddress.Loopback is 127.0.0.1, IPAddress.Any means all interfaces, IPAddress.IPv6Loopback is ::1. |
port |
0 to 65535. Use 0 in a listener to let the OS pick a free port, then read it from LocalEndpoint. |
backlog |
Queue length for pending connections. |
SocketShutdown |
Send, Receive or Both: closes one direction of the connection. |
ReceiveTimeout, SendTimeout |
Milliseconds before a blocking synchronous call throws. Async calls use a CancellationToken instead. |
Returns: ReceiveAsync returns the number of bytes read, and 0 means the other side closed the connection.
Errors: SocketException with a SocketErrorCode such as ConnectionRefused, ConnectionReset, TimedOut or AddressAlreadyInUse; IOException from a NetworkStream wrapping a socket error; ObjectDisposedException after closing.
Usage notes
- Frame your messages. Use
ReadLinefor text protocols, a length prefix for binary ones, or a fixed record size. Never assume oneReceiveequals oneSend. Receivereturns what is available. A return value of 0 means the peer closed; any positive number can be smaller than the buffer. Loop until you have the bytes you need (the second example does so;Stream.ReadExactlyAsyncdoes the same on aNetworkStream).- Accept in a loop, handle in a task. A server calls
AcceptTcpClientAsyncrepeatedly and starts a task for each client so one slow client does not block the others. - Dispose everything.
TcpClient,NetworkStreamandSocketareIDisposable. Closing the stream closes the connection. Forgotten connections eventually exhaust the available ports. - Port reuse. After a listener stops, the port can remain unavailable for a short time. Bind to port 0 in tests, or set
ExclusiveAddressUseandReuseAddressdeliberately. NoDelay. Nagle's algorithm batches small writes. SetNoDelay = truefor latency-sensitive request/response protocols; leave it off for bulk transfers.- Security. Plain TCP is unencrypted. Wrap the
NetworkStreaminSslStreamfor TLS. Limit message sizes (check a length prefix before allocating) and apply timeouts, or a malicious client can exhaust memory or hold connections forever. - IPv4 and IPv6.
new TcpListener(IPAddress.IPv6Any, port)with dual-mode accepts both.TcpClient.ConnectAsync(host, port)tries each address a name resolves to. - Higher-level options first. For HTTP use
HttpClient/Kestrel, for streaming parsers considerSystem.IO.Pipelines, and for WebSockets useClientWebSocket. Raw sockets are for custom protocols. - The sandbox here. Only loopback connections work on this site's runner. Binding to other interfaces or reaching the internet fails.