Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Sockets in C#

Introduction

Sockets are endpoints for communication between two machines. Using sockets, programs can communicate across a network. In C#, sockets are extensively used for network programming. This tutorial will guide you through the basics of socket programming in C#.

Understanding Sockets

A socket is one end of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the Transmission Control Protocol (TCP) layer can identify the application that data is destined to. Here are some basic terms and concepts:

  • IP Address: A unique string of numbers separated by periods that identifies each computer using the Internet Protocol to communicate over a network.
  • Port Number: A port number is a 16-bit unsigned integer ranging from 0 to 65535. Ports are used to distinguish different types of traffic.
  • TCP: Transmission Control Protocol is a standard that defines how to establish and maintain a network conversation through which applications can exchange data.
  • UDP: User Datagram Protocol is a simpler message-based connectionless protocol.

Creating a Simple Server

Let's start by creating a simple server socket in C#. The server will listen for incoming connections and respond to them.

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

class Program
{
    static void Main()
    {
        // Define the endpoint and port
        IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 11000);

        // Create a Socket
        Socket listener = new Socket(IPAddress.Any.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

        try
        {
            // Bind the socket to the endpoint
            listener.Bind(localEndPoint);

            // Start listening for connections
            listener.Listen(10);

            Console.WriteLine("Waiting for a connection...");
            Socket handler = listener.Accept();

            // Incoming data from the client
            string data = null;
            byte[] bytes = new Byte[1024];

            int bytesRec = handler.Receive(bytes);
            data += Encoding.ASCII.GetString(bytes, 0, bytesRec);

            // Show the data on the console
            Console.WriteLine("Text received : {0}", data);

            // Echo the data back to the client
            byte[] msg = Encoding.ASCII.GetBytes(data);
            handler.Send(msg);

            handler.Shutdown(SocketShutdown.Both);
            handler.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
}
                

Creating a Simple Client

Now, let’s create a client that will connect to the server and send a message.

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

class Program
{
    static void Main()
    {
        byte[] bytes = new byte[1024];

        try
        {
            // Connect to a remote device
            IPHostEntry host = Dns.GetHostEntry("localhost");
            IPAddress ipAddress = host.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);

            // Create a TCP/IP socket
            Socket sender = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            // Connect to the remote endpoint
            sender.Connect(remoteEP);

            Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString());

            // Encode the data string into a byte array
            byte[] msg = Encoding.ASCII.GetBytes("Hello Server!");

            // Send the data through the socket
            int bytesSent = sender.Send(msg);

            // Receive the response from the remote device
            int bytesRec = sender.Receive(bytes);
            Console.WriteLine("Echoed test = {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));

            // Release the socket
            sender.Shutdown(SocketShutdown.Both);
            sender.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
}
                

Running the Server and Client

To see the server and client in action, follow these steps:

  1. Run the server program first. It will start listening for incoming connections.
  2. Run the client program. It will connect to the server and send a message.
  3. The server will receive the message and echo it back to the client.
  4. The client will display the echoed message from the server.

Conclusion

In this tutorial, we covered the basics of socket programming in C#. We created a simple server that listens for incoming connections and a client that connects to the server and sends a message. Socket programming is a powerful tool for network communication and is used in various applications, from web servers to chat applications.