1. Introduction
Every.NET application that talks to an API, database, or another service uses sockets. Understanding TCP Sockets helps you write better APIs, microservices, and real-time apps.
2. What is a TCP Socket?
TCP (Transmission Control Protocol) is a reliable, connection-oriented protocol. A Socket is the endpoint of that connection. One socket listens (Server), the other connects (Client).
Flow: Server starts and Listens on IP:Port -> Client Connects -> 3-Way Handshake -> Data exchange via NetworkStream -> Connection Closed.
3. Implementation in.NET
.NET provides TcpListener for server and TcpClient for client in System.Net.Sockets namespace.
Server Code (TcpListener)
C#
using System.Net;using System.Net.Sockets;using System.Text;
var listener = new TcpListener(IPAddress.Any, 5000);listener.Start();Console.WriteLine("Server started on port 5000...");
while (true){ var client = await listener.AcceptTcpClientAsync(); Console.WriteLine("Client connected!");
using var stream = client.GetStream(); byte[] buffer = new byte[1024]; int bytesRead = await stream.ReadAsync(buffer); string message = Encoding.UTF8.GetString(buffer, 0, bytesRead); Console.WriteLine($"Received: {message}");
string response = $"Server received: {message}"; byte[] responseData = Encoding.UTF8.GetBytes(response); await stream.WriteAsync(responseData);}
18 lines hidden
Client Code (TcpClient)
C#
using System.Net.Sockets;using System.Text;
using var client = new TcpClient();await client.ConnectAsync("127.0.0.1", 5000);
using var stream = client.GetStream();string message = "Hello from.NET Client";byte[] data = Encoding.UTF8.GetBytes(message);await stream.WriteAsync(data);
byte[] buffer = new byte[1024];int bytesRead = await stream.ReadAsync(buffer);string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);Console.WriteLine(response);
10 lines hidden
4. Key Points for.NET Developers
- Always use Async: Use
AcceptTcpClientAsync,ReadAsync,WriteAsyncto avoid blocking threads. - Use
using: Sockets hold unmanaged resources. Always dispose them. - Higher Abstraction: For REST APIs, use
HttpClient. For real-time, useSignalR. Both internally use sockets.
5. Real-World Use Case
Chat apps, multiplayer games, IoT devices, custom microservice communication where HTTP is too heavy.