How to implement sockets in C#
Socket is a type of communication channel to help different systems communicate with each other. Socket programming is a way of developing programs where systems can exchange messages through sockets. It is implemented in multiple languages, including C, Java, Ruby, and JavaScript etc.
There are two sides to socket programming: client and server.
Server-side
Server is the system that fulfills the request of a client. It provides resources to the clients and ensures communication between multiple clients through sending and receiving messages.
We can implement a socket on a server using the following
using System;using System.Net;using System.Net.Sockets;using System.Text;
We import all the necessary namespaces.
public class Server{public static void Main(){
We create our
Serverclass and declare aMainmethod in it that executes our code.
IPAddress serverAddress = IPAddress.Parse("12.0.0.7");int serverPort = 8000;
We store the IP address and port number used by our server.
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
We create our socket using the socket class. The parameters in the class:
AddressFamily.InterNetworktells that our socket uses IPv4 address,SocketType.StreamandProtocolType.cptells that the connection type is TCP.
serverSocket.Bind(new IPEndPoint(serverAddress, serverPort));
We connect our socket with the IP address and port of the server using the
Bindfunction.
serverSocket.Listen(5);
The
Listenmethod makes the server active and ready to accept incoming client connections. The parameter in the function denotes the maximum number of pending connections that theserverSocketcan line up before it starts rejecting new connections.
Socket clientSocket = serverSocket.Accept();
We call the function
Acceptto accept the incoming client connection. This function returns the connected shared socket between the client and the server stored in variableclientSocket.
byte[] temp = new byte[1024];int clientBytes = clientSocket.Receive(temp);string clientMessage = Encoding.ASCII.GetString(temp, 0, clientBytes);
We create a byte array
tempto store bytes sent by the client. The functionReceivereceives a message sent by the client. The message received is in byte format so it is converted to a string and stored in variableclientMessage.
string serverMessage = "Hello, client!";byte[] temp2 = Encoding.ASCII.GetBytes(serverMessage);clientSocket.Send(temp2);
The string
serverMessagecontains the message to be sent to the client by the server. It is converted to byte format and stored in byte arraytemp2. TheSendfunction, sends the message to the client in the byte format.
clientSocket.Shutdown(SocketShutdown.Both);clientSocket.Close();serverSocket.Close();
In the last step, we use the
ShutdownandClosemethod to discontinue the connection between the client and the server and then close the sockets of the client and server, respectively.
Client-side
The client sends the request to the server to use its services. After establishing a connection between the client and server, they can exchange messages and data.
We can implement a socket on the client-side using the following steps.
using System;using System.Net;using System.Net.Sockets;using System.Text;
We import all the necessary namespaces.
public class Client{public static void Main(){
We create our
Clientclass and declare aMainmethod in it that executes our code.
IPAddress serverAddress = IPAddress.Parse("12.0.0.7");int serverPort = 8000;
We store the IP address and port number used by our server. We will use this information to send a request to this specific server.
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
We create our socket using the socket class. The parameters in the class:
AddressFamily.InterNetworktell that the socket uses IPv4 address,SocketType.StreamandProtocolType.cptells that the connection type is TCP.
clientSocket.Connect(new IPEndPoint(serverIP, serverPort));
We send a connection request to the server using the
Connectfunction. We send the port number and IP address of the server as the parameter.
string clientMessage = "Hello, server!";byte[] temp = Encoding.ASCII.GetBytes(clientMessage);clientSocket.Send(temp);
The string
clientMessagecontains the message we send to the server. It is converted to byte format and stored in the byte arraytemp. The functionSendsends the message to the client in the byte format.
byte[] temp2 = new byte[1024];int serverBytes = clientSocket.Receive(temp2);string serverMessage = Encoding.ASCII.GetString(temp2, 0, serverBytes);
We create a byte array
temp2to store bytes sent by the server. We read the client's message using theReceivefunction. The message received is in byte format so it is converted to a string ans stored in variableserverMessage.
clientSocket.Shutdown(SocketShutdown.Both);clientSocket.Close();
In the last step, we use the
ShutdownandClosemethod to discontinue the connection between the client and the server and then close the client's socket respectively.
Implementation
The following code example shows the working of the client-server model we learned above in the Answer.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class Client
{
public static void Main()
{
// Setting up the server IP address and port number
IPAddress serverAddress = IPAddress.Parse("127.0.0.7");
int serverPort = 8000;
// Creating our client socket
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Connecting to the server
clientSocket.Connect(new IPEndPoint(serverAddress,serverPort));
Console.WriteLine("Connected to server!");
// Sending message to the server
string clientMessage = "Hello, server!";
byte[] temp = Encoding.ASCII.GetBytes(clientMessage);
clientSocket.Send(temp);
// Receiving message from the server
byte[] temp2 = new byte[1024];
int serverBytes = clientSocket.Receive(temp2);
string serverMessage = Encoding.ASCII.GetString(temp2, 0, serverBytes);
Console.WriteLine("Received response from server: " + serverMessage);
// Closing the connection
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
}
Conclusion
Socket programming in C# allows the developers to communicate between different systems over a network. They can establish connections and exchange messages using the server and client side.
Free Resources