C# Socket Programming

Introduction:

C# stands out as a robust and widely embraced programming language renowned for its versatility in crafting diverse applications. A key advantage lies in its adeptness at handling Socket programming, empowering developers to fashion applications capable of interacting with external devices or software through Network connections. This guide delves into the fundamental aspects of C# Socket programming and illuminates its role in constructing Networked applications.

What are Sockets?

If two software applications are operating within the same network and engage in bidirectional communication through a shared link, their communication endpoint is identified as a Socket. A Socket is defined by its IP Address, Port Number, and Protocol. It facilitates the establishment of a connection, transmission and reception of data, and termination of the connection.

Types of Sockets:

There exist two primary categories of Sockets: Stream Sockets and Datagram Sockets. Stream Sockets operate in a connection-oriented manner, facilitating dependable, bidirectional communication between devices. These sockets guarantee that the sequence of data transmission remains unchanged. Datagram Sockets, on the other hand, function in a connectionless fashion, enabling an unreliable, unidirectional exchange of data between devices. These sockets do not ensure that the received data retains the same order as it was sent.

What is Socket Programming?

Socket programming is a method utilized to facilitate communication between two applications across a network. It consists of establishing a socket, which acts as a virtual endpoint enabling the exchange of data over the network. The communication between the two applications occurs by transmitting data through their individual sockets, which are linked through the network.

C# Socket Programming Basics:

Before delving into the details of C# Socket Programming, it is crucial to grasp fundamental principles of Socket programming overall. A Socket serves as a software endpoint representing one terminal of a bidirectional Communication pathway connecting two Network-oriented applications. It is characterized by an IP Address and a Port Number, which together uniquely designate the Socket.

In C#, the Socket class offers functionality for generating and controlling Sockets. This class is located within the System.Net.Sockets namespace and offers a range of methods and attributes that empower you to establish, set up, establish connections, transmit, and receive data across a Network.

To utilize Sockets in C#, the initial step is to import the System.Net.Sockets namespace. The Socket class is employed for the creation and management of Sockets.

The code snippet below demonstrates the process of instantiating a fresh Socket in C#:

Example

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

The AddressFamily parameter defines the addressing format utilized by the Socket. The SocketType parameter indicates the category of the Socket. The ProtocolType parameter details the communication protocol employed by the Socket.

The Connect function is essential for establishing a connection between two devices. Below is the code snippet demonstrating how to establish a connection with a remote device through C# Socket Programming:

Example

IPAddress ipAddress = IPAddress.Parse("192.168.1.1");
IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, 80);
socket.Connect(remoteEndPoint);

The IPAddress parameter indicates the specific IP Address of the distant device. The IPEndPoint parameter defines the endpoint of the remote device.

To transfer data via a Socket, the Send function is employed. Below is an example demonstrating the transmission of data over a Socket using C# Socket Programming:

Example

byte[] data = Encoding.ASCII.GetBytes("Hello World");
socket.Send(data);

The byte argument indicates the information to be transmitted. The Encoding.ASCII.GetBytes function is employed to transform the text "Hello World" into a byte array.

To obtain data over a Socket, the Receive function is employed. Below is an example demonstrating the reception of data over a socket through C# Socket Programming:

Example

byte[] data = new byte[1024];
int receivedBytes = socket.Receive(data);
string receivedData = Encoding.ASCII.GetString(data, 0, receivedBytes);

The byte argument indicates the buffer where the data will be stored. The integer parameter defines the maximum byte size to be received. To convert the byte array into a string, the method Encoding.ASCII.GetString is employed.

To terminate a connection, you can employ the Close method. Below is an example demonstrating the closure of a connection in C# Socket Programming:

Example

socket.Close();

C# Socket Programming Example

C# Code:

Example

// Server code
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(IPAddress.Any, 1234));
serverSocket.Listen(10);
Socket clientSocket = serverSocket.Accept();
byte[] data = new byte[1024];
int receivedBytes = clientSocket.Receive(data);
string receivedMessage = Encoding.ASCII.GetString(data, 0, receivedBytes);
Console.WriteLine("Received message: " + receivedMessage);
clientSocket.Send(Encoding.ASCII.GetBytes("Hello from server!"));
clientSocket.Close();
serverSocket.Close();

// Client code
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(new IPEndPoint(IPAddress.Loopback, 1234));
clientSocket.Send(Encoding.ASCII.GetBytes("Hello from client!"));
byte[] data = new byte[1024];
int receivedBytes = clientSocket.Receive(data);
string receivedMessage = Encoding.ASCII.GetString(data, 0, receivedBytes);
Console.WriteLine("Received message: " + receivedMessage);
clientSocket.Close();

In this scenario, the server is actively monitoring for incoming connections on port 1234, while the client initiates a connection to the server using the loopback address (localhost) and port 1234. After the connection is successfully established, the client transmits data to the server, which in turn replies with a message. Ultimately, both the client and server proceed to close their respective Sockets.

Input Required

This code uses input(). Please provide values below: