Thursday, June 5, 2014

What is socket, how to send data over TCP/IP

TCP/IP provides end to end connectivity specifying how data should be formatted, addressed, transmitted, routed, and received at the destination. It can be used in the internet and in stand-alone private networks.

TCP (Transmission Control Protocol) is reliable and byte-stream channel similar to file I/O. It is connection oriented and bidirectional communication. Used for a large data capacity and persistent connection.

Socket is known as an internet address, a port number and end to end protocol.

Before start this, you should be aware about the system port. For communication you need an open port on server. You can have 65,535 number of TCP port on your system. You can find the open port by using this command.

Goto Start >>> type cmd in RUN.  Write the command in command prompt.
netstat -an


  
You can also check the specific port by writing this command             

netstat -an|find “13000”

Now work start here. You have a server with known IP address and open port number. Create two project, one for server that will listen to the client, and other for client that make requests.
Add the following name space in server side code:

using System.Net.Sockets;
using System.Net;

Also add this code in Server side.

private void FrmTCPServerListenser_Load(object sender, EventArgs e)
        {
           TcpListener server = null;
            try
            {
                //add your server ip here
                IPAddress localAddr = IPAddress.Parse("127.0.0.1");

                // create tcp listener object and pass it server ip and open port.
                server = new TcpListener(localAddr, 13000);

                // start server to listen on the port.
                server.Start();

                // Buffer data
                Byte[] Requestbytes=new Byte[1024];
                String strData = null;

                // listening Request.
                while (true)
                {
                    // accept connection from client                  
                    TcpClient client = server.AcceptTcpClient();

                    strData = string.Empty ;

                    // Get a stream object for reading and writing
                    NetworkStream stream = client.GetStream();
                   
                   
                    int i;

                    // receive data from client in loop to the end of byte
                    while ((i = stream.Read(Requestbytes, 0, Requestbytes.Length)) != 0)
                    {
                        //Convert byte into text
                        strData = System.Text.Encoding.ASCII.GetString(Requestbytes, 0, i);

                        listBox1.Items.Add(strData);
                    
                        //convert text into byte
                        byte[] msg = System.Text.Encoding.ASCII.GetBytes("Message Received");

                        // send back response to the client.
                        stream.Write(msg, 0, msg.Length);
                      
                    }

                    // close connection
                    client.Close();
                }
            }
            catch (SocketException ez)
            {
              
            }
            finally
            {
                // Stop listening
                server.Stop();
            }

                
        }

Now run the server app on server and write this code for client application.
private void btnSend_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtMessage.Text.Trim()))
                return;
               

                //Create a TCP client
                TcpClient client = new TcpClient("127.0.0.1", 13000);

                // convert message into byte.
                Byte[] data = System.Text.Encoding.ASCII.GetBytes(txtMessage.Text);

              
                //Network stream for Read and Write
                NetworkStream Netstream = client.GetStream();

                // Send the message to the connected TcpServer.
                Netstream.Write(data, 0, data.Length);


                // byte to get the response
                data = new Byte[256];

                String responseData = String.Empty;

                // read the response.
                Int32 bytes = Netstream.Read(data, 0, data.Length);
                responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
              
                MessageBox.Show(responseData);
                // Close stream and connection
                Netstream.Close();
                client.Close(); 
               
        }

On button click event a message will be sent to the server.
Remember that server application must be running before client apps.




Search This Blog