Socket Programming in C#

Socket programming in C# enables network communication between applications using the System.Net.Sockets namespace. This namespace provides a managed implementation of the Windows Sockets interface for creating client-server applications that communicate over TCP/IP networks.

Socket programming has two basic modes − synchronous (blocking) and asynchronous (non-blocking) operations.

Socket Class Constructor Syntax

Following is the syntax for creating a Socket instance −

Socket socket = new Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType);

Parameters

  • AddressFamily − Specifies the addressing scheme (InterNetwork for IPv4, InterNetworkV6 for IPv6)

  • SocketType − Defines the type of socket (Stream for TCP, Dgram for UDP)

  • ProtocolType − Specifies the network protocol (Tcp, Udp, etc.)

Using TcpListener for Server Applications

The TcpListener class simplifies creating TCP server applications by handling incoming client connections −

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class TcpServer {
   public static void Main() {
      TcpListener listener = new TcpListener(IPAddress.Any, 8080);
      listener.Start();
      Console.WriteLine("Server started on port 8080");
      
      Socket clientSocket = listener.AcceptSocket();
      Console.WriteLine("Client connected: " + clientSocket.RemoteEndPoint);
      
      byte[] data = new byte[1024];
      int receivedBytes = clientSocket.Receive(data);
      string message = Encoding.ASCII.GetString(data, 0, receivedBytes);
      Console.WriteLine("Received: " + message);
      
      string response = "Hello from server!";
      clientSocket.Send(Encoding.ASCII.GetBytes(response));
      
      clientSocket.Close();
      listener.Stop();
   }
}

The output of the above code is −

Server started on port 8080
Client connected: 127.0.0.1:54321
Received: Hello Server

Using TcpClient for Client Applications

The TcpClient class provides a simple way to create TCP client connections −

using System;
using System.Net.Sockets;
using System.Text;

class TcpClientExample {
   public static void Main() {
      try {
         TcpClient client = new TcpClient("127.0.0.1", 8080);
         Console.WriteLine("Connected to server");
         
         NetworkStream stream = client.GetStream();
         
         string message = "Hello Server";
         byte[] data = Encoding.ASCII.GetBytes(message);
         stream.Write(data, 0, data.Length);
         Console.WriteLine("Sent: " + message);
         
         byte[] buffer = new byte[1024];
         int bytesRead = stream.Read(buffer, 0, buffer.Length);
         string response = Encoding.ASCII.GetString(buffer, 0, bytesRead);
         Console.WriteLine("Received: " + response);
         
         stream.Close();
         client.Close();
      }
      catch (Exception e) {
         Console.WriteLine("Error: " + e.Message);
      }
   }
}

The output of the above code is −

Connected to server
Sent: Hello Server
Received: Hello from server!

Using Socket Class Directly

For more control over network communication, you can use the Socket class directly −

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class SocketExample {
   public static void Main() {
      Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      
      IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);
      
      try {
         socket.Connect(endPoint);
         Console.WriteLine("Socket connected to: " + socket.RemoteEndPoint);
         
         string message = "Hello from Socket";
         byte[] data = Encoding.ASCII.GetBytes(message);
         socket.Send(data);
         
         byte[] buffer = new byte[1024];
         int receivedBytes = socket.Receive(buffer);
         string response = Encoding.ASCII.GetString(buffer, 0, receivedBytes);
         Console.WriteLine("Server response: " + response);
         
         socket.Shutdown(SocketShutdown.Both);
         socket.Close();
      }
      catch (Exception e) {
         Console.WriteLine("Exception: " + e.Message);
      }
   }
}

The output of the above code is −

Socket connected to: 127.0.0.1:8080
Server response: Hello from server!

Comparison of Socket Programming Approaches

Class Use Case Complexity Control Level
TcpListener Simple TCP servers Low Medium
TcpClient Simple TCP clients Low Medium
Socket Advanced networking High Full

Conclusion

Socket programming in C# provides multiple approaches for network communication. Use TcpListener and TcpClient for simple TCP applications, while the Socket class offers complete control for advanced networking scenarios. Choose the appropriate class based on your application's complexity and control requirements.

Updated on: 2026-03-17T07:04:35+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements