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.

Server

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
 
namespace TcpServer
{
    class ServerClass
    {
      
        static void 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();
            user.SendMessage(Message);
 
        }
    }
 
    class ClientClass
    {
        TcpClient Client;
        byte[] Data;
        bool Flag = true;
        NetworkStream netStream;
 
        // When a client comes in.
        public ClientClass(TcpClient newClient)
        {
            Client = newClient;
 
            Console.WriteLine("Connected with " + Client.Client.RemoteEndPoint);
 
            // To notify the client about his connection.
            SendMessage("Connected.");
 
            // For receiving the data.       
            Data = new byte[100];
            netStream = Client.GetStream();
            netStream.BeginRead(Data, 0, 100, ReceiveMessage, null);
        }
 
        // Read from clients.
        public void ReceiveMessage(IAsyncResult ar)
        {
            int bufferLength;
            try
            {
                bufferLength = Client.GetStream().EndRead(ar);
 
                // Receive the message from client side.
                string messageReceived = Encoding.ASCII.GetString(Data, 0,
 bufferLength);
 
                // Display it on server's console.

Console.WriteLine(Client.Client.RemoteEndPoint.ToString() + "-> "

+ messageReceived);

 
                // Continue reading from client. 
                Client.GetStream().BeginRead(Data, 0, 100, ReceiveMessage, null);
            }
            catch(Exception ex)
            {
                Console.WriteLine(Client.Client.RemoteEndPoint.ToString() + " 
is disconnected.");
            }
        }
 
        // Send the message.
        public void SendMessage(string message)
        {
            try
            {
                byte[] bytesToSend = System.Text.Encoding.ASCII.GetBytes(message);
                Client.Client.Send(bytesToSend);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }
}

Client

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
 
 
namespace Client
{
    class Program
    {
 
        static void Main(string[] args)
        {
            ClientMech ObjClient = new ClientMech();
 
            string Message = Console.ReadLine();
            ObjClient.SendMessage(Message);
        }
    }
 
    class ClientMech
    {
        TcpClient Client;
        byte[] Data;
 
        public ClientMech()
        {
            Client = new TcpClient();
            Client.Connect("127.0.0.1", 1986);
            Data = new byte[100];
 
            // Reading from server.
            Client.GetStream().BeginRead(Data, 0, 100, ReceiveMessage, null);
 
        }
 
        public void SendMessage(string message)
        {
            try
            {
 
                NetworkStream netStr = Client.GetStream();
                byte[] Data = System.Text.Encoding.ASCII.GetBytes(message);
                netStr.Write(Data, 0, Data.Length);
                netStr.Flush();
 
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
 
        }
 
        // Receive message from the server.
        public void ReceiveMessage(IAsyncResult ar)
        {
            int bufferLength;
            try
            {
                bufferLength = Client.GetStream().EndRead(ar);
                

string message = (System.Text.Encoding.ASCII.GetString(Data,

0, bufferLength)).ToString();

                Console.WriteLine(Client.Client.RemoteEndPoint.ToString()
 + "-> " + message);
                
                // Continue reading from the server.
                Client.GetStream().BeginRead(Data, 0, 100, ReceiveMessage, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }
}

In my next post, I will be writing about creating of an Instant LAN Messenger so till then, stay tuned!

Related Stories