Monday, January 14, 2013

Socket Program in c-sharp

Client and server implementation using socket programming:

Socket -- an End-Point of To and From (Bidirectional) communication link between two programs (Server Program and Client Program ) running on the same network.
Details:Two programs are needed for communicating a socket application in C# using TCP/IP Communication protocol.
A Server Socket Program ( Server ) and a Client Socket Program ( Client ) .
Server Socket Program running on a computer has a socket bound to a Port Number on the same computer and listening to the client's incoming requests.
 Client Socket Program have to know the IP Address ( Hostname ) of the computer that the C# Server Socket Program resides.
Once the connection is established between Server and Client , they can communicate (read or write ) through their own sockets.
Start the server and then make a connection to server by invoking the client..
Both client and server are on the same machine.
Two types of communication protocol can beused for Socket Programming in C#: 
  1.  TCP/IP ( Transmission Control Protocol/Internet protocol ) Communication
  2.  UDP/IP ( User Datagram Protocol/Internet protocol ) Communication .
 Server Implementation:Below is the source code for server implementation

using System.Net.Sockets:
namespace Server
{
    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();
        }
    }
}

Client Implementation:Drag textbox,label and button control and drop them on form.In the code behind paste the following code
using System.Net.Sockets;
namespace Client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
        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 ...";
        }
       

        public void msg(string mesg)
        {
            textBox1.Text = textBox1.Text + Environment.NewLine + " --> " + mesg;
        }

        private void button1_Click_1(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);
        }
    }
}
Images:
1. Form Design:
2.  Client server snapshot (running mode)


Enjoy coding!!!!!

No comments: