Socket programming is a way of connecting two nodes on a network to communicate with each other. Basically, it is a one-way Client and Server setup where a Client connects, sends messages to the server and the server shows them using socket connection. One socket (node) listens on a particular port at an IP, while other socket reaches out to the other to form a connection. Server forms the listener socket while the client reaches out to the server. Before going deeper into Server and Client code, it is strongly recommended to go through TCP/IP Model.
Client Side Programming
Before creating client's socket a user must decide what 'IP Address' that he want to connect to, in this case, it is the localhost. At the same time, we also need the 'Family' method that will belong to the socket itself. Then, through the 'connect' method, we will connect the socket to the server. Before sending any message, it must be converted into a byte array. Then and only then, it can be sent to the server through the 'send' method. Later, thanks to the 'receive' method we are going to get a byte array as answer by the server. It is notable that just like in the C language, the 'send' and 'receive' methods still return the number of bytes sent or received.
C#
// A C# program for Client
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Client {
class Program {
// Main Method
static void Main(string[] args)
{
ExecuteClient();
}
// ExecuteClient() Method
static void ExecuteClient()
{
try {
// Establish the remote endpoint
// for the socket. This example
// uses port 11111 on the local
// computer.
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 11111);
// Creation TCP/IP Socket using
// Socket Class Constructor
Socket sender = new Socket(ipAddr.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try {
// Connect Socket to the remote
// endpoint using method Connect()
sender.Connect(localEndPoint);
// We print EndPoint information
// that we are connected
Console.WriteLine("Socket connected to -> {0} ",
sender.RemoteEndPoint.ToString());
// Creation of message that
// we will send to Server
byte[] messageSent = Encoding.ASCII.GetBytes("Test Client<EOF>");
int byteSent = sender.Send(messageSent);
// Data buffer
byte[] messageReceived = new byte[1024];
// We receive the message using
// the method Receive(). This
// method returns number of bytes
// received, that we'll use to
// convert them to string
int byteRecv = sender.Receive(messageReceived);
Console.WriteLine("Message from Server -> {0}",
Encoding.ASCII.GetString(messageReceived,
0, byteRecv));
// Close Socket using
// the method Close()
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
// Manage of Socket's Exceptions
catch (ArgumentNullException ane) {
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se) {
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e) {
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
}
}
Server Side Programming
In the same way, we need an 'IP address' that identifies the server in order to let the clients to connect. After creating the socket, we call the 'bind' method which binds the IP to the socket. Then, call the 'listen' method. This operation is responsible for creating the waiting queue which will be related to every opened 'socket'. The 'listen' method takes as input the maximum number of clients that can stay in the waiting queue. As stated above, there is communication with the client through 'send' and 'receive' methods.
Note: Don't forget the conversion into a byte array.
C#
// A C# Program for Server
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Server {
class Program {
// Main Method
static void Main(string[] args)
{
ExecuteServer();
}
public static void ExecuteServer()
{
// Establish the local endpoint
// for the socket. Dns.GetHostName
// returns the name of the host
// running the application.
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 11111);
// Creation TCP/IP Socket using
// Socket Class Constructor
Socket listener = new Socket(ipAddr.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try {
// Using Bind() method we associate a
// network address to the Server Socket
// All client that will connect to this
// Server Socket must know this network
// Address
listener.Bind(localEndPoint);
// Using Listen() method we create
// the Client list that will want
// to connect to Server
listener.Listen(10);
while (true) {
Console.WriteLine("Waiting connection ... ");
// Suspend while waiting for
// incoming connection Using
// Accept() method the server
// will accept connection of client
Socket clientSocket = listener.Accept();
// Data buffer
byte[] bytes = new Byte[1024];
string data = null;
while (true) {
int numByte = clientSocket.Receive(bytes);
data += Encoding.ASCII.GetString(bytes,
0, numByte);
if (data.IndexOf("<EOF>") > -1)
break;
}
Console.WriteLine("Text received -> {0} ", data);
byte[] message = Encoding.ASCII.GetBytes("Test Server");
// Send a message to Client
// using Send() method
clientSocket.Send(message);
// Close client Socket using the
// Close() method. After closing,
// we can use the closed Socket
// for a new Client Connection
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
}
catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
}
}
To run on Terminal or Command Prompt:
- First save the files with .cs extension. Suppose we saved the files as client.cs and server.cs.
- Then compile both the files by executing the following commands:
$ csc client.cs
$ csc server.cs
- After successful compilation opens the two cmd one for Server and another for Client and first try to execute the server as follows

- After that on another cmd execute the client code and see the following output on the server side cmd.

- Now you can see the changes on the server as soon as the client program executes.

Similar Reads
Learn C# Programming
This C# Learning Guide is perfect for both beginners and experienced programmers. This specially designed, free online guide will help you learn C# programming efficiently from scratch, covering all topics from basics to advanced, including web development, the .NET framework, and more, with real-wo
15+ min read
Network Programming Python - HTTP Server
HTTP Web Server is simply a process which runs on a machine and listens for incoming HTTP Requests by a specific IP and Port number, and then sends back a response for the request. Python has a built-in webserver provided by its standard library, can be called for simple client-server communication.
3 min read
Introduction to C#
C# (C-sharp) is a modern, object-oriented programming language developed by Microsoft as part of the .NET framework. It was first released in 2000 and it has become one of the most widely used languages for building Windows applications, web services, and more. C# combines the power of C and C++ wit
7 min read
C# Program to Print Hello World Without Using WriteLine
Hello World program is the most basic program of any programming language. It prints "Hello world" on the screen. In this article, we will display "Hello World" without using WriteLine Method. So to do this task we use the following methods: Console.OpenStandardOutput(): This method is used to acqui
2 min read
C# Program to Find the IP Address of the Machine
An IP address is known as an Internet Protocol address. It is a unique address that identifies the device over the network. It is almost like a set of rules which govern the data sent over the Internet or through a local network. It helps the Internet to distinguish between routers, computers, websi
3 min read
Basics of FileStream in C#
The FileStream is a class used for reading and writing files in C#. It is part of the System.IO namespace. To manipulate files using FileStream, you need to create an object of FileStream class. This object has four parameters; the Name of the File, FileMode, FileAccess, and FileShare. The Syntax to
4 min read
Implementing UDP Through C#
UDP stands for User Datagram Protocol. It is a connectionless protocol. When you send data or message, you don't know if it will get there, it could get lost on the way. There may be corruption while transferring a message. UDP does not use streaming and it uses datagrams instead of streams. It is l
2 min read
C# Multithreading
C# is a multi-paradigm programming language that supports several programming styles, including procedural, object-oriented, and functional programming. One of the essential features of C# is its support for multithreading, which enables developers to write applications that can perform multiple tas
9 min read
Establishing Client Server Relationship Through C#
At the point when the server program is run, it will demonstrate at which IP it is running and the port it is paying attention to. Presently run the client program is run, in order to lay out an association with the server. At the point when an association is laid out, the server will show the IP ad
3 min read
C# Main Thread
In C#, threads are the smallest units of execution that allow parallel execution of code, enabling multiple tasks to run concurrently within a single process. The Thread class in the System.Threading namespace is used to create and manage threads. In C#, the Main method is the entry point of any con
5 min read