In this tutorial, I am going to talk about the creation of TCP/IP socket and use of this connection between applications. The client-server architecture can be local or distributed over the network. I will discuss it in a simple manner which would help you in developing a small chat-like application. Based on this tutorial, I will later explain about how to develop an Instant LAN Messenger in WPF using Socket Programming.
The .NET Framework provides us with a higher level of abstraction upon sockets in the form of TcpListener and TcpClient. TcpListener is a high level interface for server and TCPClient is for client application. They are both implemented over sockets but provides easier and high level interface. NetworkStream is used for an end to end communication between TcpListener and TcpClient. We can use both stream reader and writer over NetworkStream through StreamReader and StreamWriter.
I will use two namespaces System.Net and System.Net.Sockets which are required for Socket Programming. Basically, TCPListener class provides simple methods to listen and accepts incoming connection requests whereas, TcpClient class implements a socket for sending and receiving data using TCP.
IPAddress class provides an Internet Protocol (IP) address and is used by clients to get connected with the server.
Following is the code for Server and Client. This code can help you in applications where you are communicating with your friends on different stations in a local network environment.
staticvoid Main(string args)
IPAddress IP = IPAddress.Parse("127.0.0.1");
// Local address to listen.
TcpListener Listener = new TcpListener(IP, 1986);
// Listening from TCP clients.
Listener.Start(); // Starts listening for incoming requests.
Console.WriteLine("Server is up at port 1986");
Console.WriteLine("Waiting for the connection...");
ClientClass user = new ClientClass(Listener.AcceptTcpClient());
string Message = Console.ReadLine();
bool Flag = true;
// When a client comes in.
public ClientClass(TcpClient newClient)
Client = newClient;
Console.WriteLine("Connected with " + Client.Client.RemoteEndPoint);