Friday, June 17, 2011

How to C# Socket programming


C# simplifies the network programming through its namespaces like System.Net and System.Net.Sockets . A Socket is an End-Point of To and From (Bidirectional) communication link between two programs (Server Program and Client Program ) running on the same network . We need two programs for communicating a socket application in C#. A Server Socket Program ( Server ) and a Client Socket Program ( Client ) . C# Server Socket Program: A C# Server Socket Program running on a computer has a socket that bound to a Port Number on the same computer and listening to the client's incoming requests.
C# Client Socket Program: A C# Client Socket Program have to know the IP Address ( Hostname ) of the computer that the C# Server Socket Program resides and the Port Number assign for listening for client's request .
Once the connection is established between Server and Client , they can communicate (read or write ) through their own sockets.
csharp-server-client-socket
There are two types of communication protocol uses for Socket Programming in C# , they are TCP/IP ( Transmission Control Protocol/Internet protocol ) Communication and UDP/IP ( User Datagram Protocol/Internet protocol ) Communication .
In the following section we are going to communicate a C# Server Socket Program and C# Client Socket Program using TCP/IP Communication Protocol.


Code for Client Program
using System;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Text; 
 
namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
 
        public Form1()
        {
           InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            msg("Client Started");
            clientSocket.Connect("127.0.0.1", 8888);
            label1.Text = "Client Socket Program - Server Connected ...";
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            NetworkStream serverStream = clientSocket.GetStream();
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes("Message from Client$");
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();
 
            byte[] inStream = new byte[10025];
            serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
            string returndata = System.Text.Encoding.ASCII.GetString(inStream);
            msg("Data from Server : " + returndata);
        }
 
        public void msg(string mesg)
        {
            textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + mesg;
        } 
    }
}


Code for Server Program
using System;
using System.Net.Sockets;
using System.Text;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpListener serverSocket = new TcpListener(8888);
            int requestCount = 0;
            TcpClient clientSocket = default(TcpClient);
            serverSocket.Start();
            Console.WriteLine(" >> Server Started");
            clientSocket = serverSocket.AcceptTcpClient();
            Console.WriteLine(" >> Accept connection from client");
            requestCount = 0;
 
            while ((true))
            {
                try
                {
                    requestCount = requestCount + 1;
                    NetworkStream networkStream = clientSocket.GetStream();
                    byte[] bytesFrom = new byte[10025];
                    networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
                    string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                    dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
                    Console.WriteLine(" >> Data from client - " + dataFromClient);
                    string serverResponse = "Server response " + Convert.ToString(requestCount);
                    Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
                    networkStream.Write(sendBytes, 0, sendBytes.Length);
                    networkStream.Flush();
                    Console.WriteLine(" >> " + serverResponse);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
 
            clientSocket.Close();
            serverSocket.Stop();
            Console.WriteLine(" >> exit");
            Console.ReadLine();
        }
    }
}


csharp-server-client-socket-program
The above picture shows a Server and Client communication interfaces in C#.
C# Server Socket Program:
The Server Socket Program is done through a C# Console based application . Here the Server is listening for the Client's request , and when the C# Server gets a request from Client socket , the Server sends a response to the Client . Click the following link to see in detail of a C# Server Socket Program.
C# Client Socket Program:
The C# Client Socket Program is a windows based application . When the C# Client program execute , it will establish a connection to the C# Server program and send request to the Server , at the same time it also receive the response from C# Server . Click the following link to see in detail of C# Client Socket Program.
How to run this program ?
The C# Socket Program has two sections.
1. C# Server Socket Program
2. C# Client Socket Program
When you finish coding and build the Server and Client program , First you have to start C# Server Socket Program from DOS prompt , then you will get a message "Server Started" in your DOS screen, where the server program is running .
Next step is to start C# Client Socket Program in the same computer or other computers on the same network . When you start the client program , it will establish a connection to the Server and get a message in client screen " Client Started " , at the same time you can see a message in the Server screen "Accept connection from client" .
Now your C# Server Socket Program and C# Client Socket Program is get connected and communicated . If you want to communicate the Server and Client again , click the button in the client program , then you can see new messages in the Server and Client programs displayed.

0 comments:

Post a Comment