How to send and receive data using Socket Programming in c#.net


How to send and receive data using Socket Programming in c#.net



Server

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace Server
{
    public partial class Form1 : Form
    {
        const int MAX_CLIENTS = 10;

        public AsyncCallback pfnWorkerCallBack;
        private Socket m_mainSocket;
        private Socket[] m_workerSocket = new Socket[10];
        private int m_clientCount = 0;
        public string filename;
        public string READTEXTFILE;
        public int FILELENGHT;
        public string fileExtention;
        public delegate void delegatemessage(string messg);
        public Form1()
        {
            InitializeComponent();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                // Check the port value
                if (txtport.Text == "")
                {
                    MessageBox.Show("Please enter a Port Number");
                    return;
                }
                string portStr = txtport.Text;
                int port = System.Convert.ToInt32(portStr);

                // Create the listening socket...

                m_mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);

                // Bind to local IP Address...
                m_mainSocket.Bind(ipLocal);

                // Start listening...
                m_mainSocket.Listen(4);

                // Create the call back for any client connections...
                m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);

                UpdateControls(true);

            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }

        }
        public void OnClientConnect(IAsyncResult asyn)
        {
            try
            {
                // Here we complete/end the BeginAccept() asynchronous call
                // by calling EndAccept() - which returns the reference to
                // a new Socket object
                m_workerSocket[m_clientCount] = m_mainSocket.EndAccept(asyn);

                // Let the worker Socket do the further processing for the 
                // just connected client
                WaitForData(m_workerSocket[m_clientCount]);


                // Now increment the client count
                ++m_clientCount;

                // Display this client connection as a status message on the GUI
                String str = String.Format("Client # {0} connected", m_clientCount);

                if(m_clientCount>0)
                     label4.ForeColor = Color.Green;                  
                else                    
                     label4.ForeColor = Color.Black;
                   

                if (this.label4.InvokeRequired)
                {
                    delegatemessage d = new delegatemessage(messg);
                    this.Invoke(d, new object[] { str });
                }
                else
                {
                    this.label4.Text = str;
                }
                
                
               
                // Since the main Socket is now free, it can go back and wait for
                // other clients who are attempting to connect
                m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);

            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }

        }
        public void sendreceivedata(string data)
        {
            richTextRxMessage.Text += data;
        }
        public void messg(string msg)
        {
            label4.Text = msg;
            listClient.Items.Add(msg);
        }
        public class SocketPacket
        {
            public System.Net.Sockets.Socket m_currentSocket;
            public byte[] dataBuffer = new byte[1];
        }
        public void WaitForData(System.Net.Sockets.Socket soc)
        {
            try
            {
                if (pfnWorkerCallBack == null)
                {
                    // Specify the call back function which is to be 
                    // invoked when there is any write activity by the 
                    // connected client
                    pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
                }

                SocketPacket theSocPkt = new SocketPacket();

                theSocPkt.m_currentSocket = soc;
                // Start receiving any data written by the connected client
                // asynchronously
                soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt);
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }

        }
        // This the call back function which will be invoked when the socket
        // detects any client writing of data on the stream
        public void OnDataReceived(IAsyncResult asyn)
        {
            try
            {
                SocketPacket socketData = (SocketPacket)asyn.AsyncState;

                int iRx = 0;
                // Complete the BeginReceive() asynchronous call by EndReceive() method
                // which will return the number of characters written to the stream 
                // by the client
                iRx = socketData.m_currentSocket.EndReceive(asyn);
                char[] chars = new char[iRx + 1];

                System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
                int charLen = d.GetChars(socketData.dataBuffer, 0, iRx, chars, 0);

                String szData = new String(chars);

                if (this.richTextRxMessage.InvokeRequired)
                {
                    delegatemessage d1 = new delegatemessage(sendreceivedata);
                    this.Invoke(d1, new object[] { szData });
                }
                else
                {
                    this.richTextRxMessage.Text = szData;
                }

               // richTextRxMessage.AppendText(szData);

                // Continue the waiting for data on the Socket
                WaitForData(socketData.m_currentSocket);
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }


           /* SocketPacket theSockId = (SocketPacket)asyn.AsyncState;
            Socket socket = theSockId.m_currentSocket;

            if (!socket.Connected)
            {
                return;
            }

            try
            {
                int iRx;
                try
                {
                    iRx = socket.EndReceive(asyn);
                }
                catch (SocketException)
                {
                    MessageBox.Show("Client has been closed and cannot answer.");

                    //OnConnectionDroped(socket);
                    return;
                }

                if (iRx == 0)
                {
                    MessageBox.Show("Client socket has been closed.");

                    OnConnectionDroped(socket);
                    return;
                }

                RaiseMessageRecived(theSockId.dataBuffer);
                // Wait for the next package
                WaitForData(m_socWorker);
            }
            catch (Exception ex)
            {
                Debug.Fail(ex.ToString(), "OnClientConnection: Socket failed");
            }*/




        }

        private void Form1_Load(object sender, EventArgs e)
        {
            txtipaddress.Text = GetIP();
        }
        String GetIP()
        {
            String strHostName = Dns.GetHostName();

            // Find host by name
            IPHostEntry iphostentry = Dns.GetHostByName(strHostName);

            // Grab the first IP addresses
            String IPStr = "";
            foreach (IPAddress ipaddress in iphostentry.AddressList)
            {
                IPStr = ipaddress.ToString();
                return IPStr;
            }
            return IPStr;
        }
        void CloseSockets()
        {
            if (m_mainSocket != null)
            {
                m_mainSocket.Close();
            }
            for (int i = 0; i < m_clientCount; i++)
            {
                if (m_workerSocket[i] != null)
                {
                    m_workerSocket[i].Close();
                    m_workerSocket[i] = null;
                }
            }
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            CloseSockets();
            Close();
        }
        private void UpdateControls(bool listening)
        {
            btnConnect.Enabled = !listening;
            btnDisconnect.Enabled = listening;
        }

        private void btnsend_Click(object sender, EventArgs e)
        {
            try
            {
                Object objData = richTextRxMessage.Text;
                byte[] byData = Encoding.ASCII.GetBytes(objData.ToString());
                for (int i = 0; i < m_clientCount; i++)
                {
                    if (m_workerSocket[i] != null)
                    {
                        if (m_workerSocket[i].Connected)
                        {
                            m_workerSocket[i].Send(byData);
                        }
                    }
                }

            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }

        private void txtipaddress_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnbrowse_Click(object sender, EventArgs e)
        {
            
            DialogResult dr=ofdbrowsefile.ShowDialog();
            lblfilestatus.ForeColor = Color.Black;
            if (dr == DialogResult.OK)
            {
                filename = ofdbrowsefile.FileName;
                fileExtention = Path.GetExtension(filename);
                FILELENGHT = filename.Length;
                try
                {
                    READTEXTFILE = File.ReadAllText(filename);
                  //  buffer = Encoding.ASCII.GetBytes(READTEXTFILE);

                    lblfilestatus.ForeColor = Color.Green;
                    lblfilestatus.Text = Path.GetFileName(filename);

                }
                catch (Exception ex)
                {

                    MessageBox.Show(ex.Message);

                }

            }
            else
            {
                lblfilestatus.Text = "....Empty....";
                lblfilestatus.ForeColor = Color.Black;
            }
            
        }

        private void btnfilesend_Click(object sender, EventArgs e)
        {
            try
            {
                //send file extention
                byte[] byData = Encoding.ASCII.GetBytes(fileExtention);
                
                if (SendFile(byData) == false)
                {
                    MessageBox.Show("File not send successfully !");
                    return;
                }



                int position = 0, i = 0, readbyte = 0,sendbyte;// headersize = 0, fPacketNumber = 0, totalPacket = 0;
                FileStream fspcmfl = new FileStream(filename, FileMode.Open, FileAccess.Read);

                if (fspcmfl == null)
                    return;

                byte[] RpcmwholeFile = new byte[fspcmfl.Length];

                int length = fspcmfl.Read(RpcmwholeFile, 0, RpcmwholeFile.Length);

                lbltotalbyte.Text = length.ToString() +"Bytes";
                pgbprocess.Minimum = 0;
                pgbprocess.Maximum = length;
                //int length1 = Convert.ToInt32(fspcmfl.Length);
                //start send file
                byte[] start = new byte[1];
                start[0] = (int)'S';
                
                if (SendFile(start) == false)
                {
                    MessageBox.Show("File not send successfully !");
                    return;
                }

                //send data..
                while (length > 0)
                {
                    if (length > 1000)
                    {
                        byte[] buffer = new byte[1000];
                       
                        for (i = 0; i < 1000; position++) //loop PAYLOAD_EACH_PACKET times 
                        {

                            buffer[i] = RpcmwholeFile[position];
                            i++;
                           // pgbwavfilewrite.Value = Position;
                            pgbprocess.Value = position;
                            lblsendbyte.Text = position.ToString() + "Bytes"; 
                            //lablperwavwrite.Text = (pgbwavfilewrite.Value * 100 / pgbwavfilewrite.Maximum).ToString() + "%";
                            length--;
                           


                        }
                        if (SendFile(buffer) == false)
                        {
                            MessageBox.Show("File not send successfully !");
                            return;
                        }
                        // Object objData = richTextRxMessage.Text;
                        //  byte[] byData = Encoding.ASCII.GetBytes(objData.ToString());
                       
                    }
                    else if (length <= 1000)
                    {
                        byte []buffer=new byte[length];
                        int totalbyte = 0;
                        totalbyte = position;
                        readbyte = length;
                        for (i = 0; i < readbyte; position++) //loop PAYLOAD_EACH_PACKET times 
                        {

                            buffer[i] = RpcmwholeFile[position];
                            i++;
                            // pgbwavfilewrite.Value = Position;
                            totalbyte += 1;
                            pgbprocess.Value = totalbyte;
                            lblsendbyte.Text = totalbyte.ToString() + "Bytes"; 
                            //lablperwavwrite.Text = (pgbwavfilewrite.Value * 100 / pgbwavfilewrite.Maximum).ToString() + "%";
                            length--;
                           

                        }
                        if (SendFile(buffer) == false)
                        {
                            MessageBox.Show("File not send successfully !");
                            return;
                        }
                    }
                }

                byte [] endfile=new byte[1];       
                endfile[0] = (int)'E';
                if (SendFile(endfile) == false)
                {
                    MessageBox.Show("File not send successfully !");
                    return;
                }
               

            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }
        
        public bool SendFile(byte[] data)
        {
           
            for (int j = 0; j < m_clientCount; j++)
            {
                if (m_workerSocket[j] != null)
                {
                    if (m_workerSocket[j].Connected)
                    {
                        m_workerSocket[j].Send(data);
                    }
                }
            }
            return true;
        }
    }
}

Client



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace Client
{
    public partial class Form1 : Form
    {
        byte[] m_dataBuffer = new byte[10];
        IAsyncResult m_result;
        public AsyncCallback m_pfnCallBack;
        public Socket m_clientSocket;
        public string receivefile;
        public string fileextention;
        public int bytedata =0;
        public Form1()
        {
            InitializeComponent();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            // See if we have text on the IP and Port text fields
            if (txtipaddress.Text == "" || txtport.Text == "")
            {
                MessageBox.Show("IP Address and Port Number are required to connect to the Server\n");
                return;
            }
            try
            {
                UpdateControls(false);
                // Create the socket instance
                m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // Cet the remote IP address
                IPAddress ip = IPAddress.Parse(txtipaddress.Text);
                int iPortNo = System.Convert.ToInt16(txtport.Text);
                // Create the end point 
                IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo);
                // Connect to the remote host
                m_clientSocket.Connect(ipEnd);

                if (m_clientSocket.Connected)
                {

                    UpdateControls(true);
                    //Wait for data asynchronously 
                    WaitForData();
                }
            }
            catch (SocketException se)
            {
                string str;
                str = "\nConnection failed, is the server running?\n" + se.Message;
                MessageBox.Show(str);
                UpdateControls(false);
            }
        }
        public void WaitForData()
        {
            try
            {
                if (m_pfnCallBack == null)
                {
                    m_pfnCallBack = new AsyncCallback(OnDataReceived);
                }
                SocketPacket theSocPkt = new SocketPacket();
                theSocPkt.thisSocket = m_clientSocket;

                // Start listening to the data asynchronously
                m_result = m_clientSocket.BeginReceive(theSocPkt.dataBuffer,
                                                        0, theSocPkt.dataBuffer.Length,
                                                        SocketFlags.None,
                                                        m_pfnCallBack,
                                                        theSocPkt);
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }

        }
        public class SocketPacket
        {
            public System.Net.Sockets.Socket thisSocket;
            public byte[] dataBuffer = new byte[1];
        }
        public delegate void delegatemessage(string messg);
        public void OnDataReceived(IAsyncResult asyn)
        {
            try
            {
                SocketPacket theSockId = (SocketPacket)asyn.AsyncState;
                int iRx = theSockId.thisSocket.EndReceive(asyn);
                char[] chars = new char[iRx + 1];
                Decoder d = Encoding.UTF8.GetDecoder();
                int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);

                
                String szData = new String(chars);
               // richTextRxMessage.Text = richTextRxMessage.Text + szData;
                if (this.richTextRxMessage.InvokeRequired)
                {
                    delegatemessage d1 = new delegatemessage(sendreceivedata);
                    this.Invoke(d1, new object[] { szData });
                }
                else
                {
                    this.richTextRxMessage.Text = szData;
                }

                WaitForData();
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }
        public void messg(string msg)
        {
           label4.Text = msg;
        }
        public void sendreceivedata(string data)
        {
            char[] val;
            val = data.ToCharArray();
           
            if (val[0] == 'E')
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(receivefile);
                FileStream ar = new FileStream("D:\\Projects\\" +"text"+fileextention , FileMode.Create);
                ar.Write(byteArray, 0, byteArray.Length);
                ar.Close();
                lblvalue.Text = "Complete";
                //m_clientSocket.Close();
               // m_clientSocket = null;

              
            }
            else if (val[0] == '.' || bytedata == 1 || bytedata == 2 || bytedata == 3)
            {
                fileextention += val[0].ToString();
                bytedata++;
            }
            else if (val[0] == 'S')
            {
                //Nothing
            }
            else
            {
                richTextRxMessage.Text += data;
                receivefile = richTextRxMessage.Text;
            }
        }
        private void UpdateControls(bool connected)
        {
            btnConnect.Enabled = !connected;
            btnDisconnect.Enabled = connected;
            string connectStatus = connected ? "Connected" : "Not Connected";
            if (connectStatus == "Connected")
            {
                label3.ForeColor = Color.Green;
            }
            else
            {
                label3.ForeColor = Color.Black;
            }
            label3.Text = connectStatus;
        }
        String GetIP()
        {
            String strHostName = Dns.GetHostName();

            // Find host by name
            IPHostEntry iphostentry = Dns.GetHostByName(strHostName);

            // Grab the first IP addresses
            String IPStr = "";
            foreach (IPAddress ipaddress in iphostentry.AddressList)
            {
                IPStr = ipaddress.ToString();
                return IPStr;
            }
            return IPStr;
        }

        private void btnsend_Click(object sender, EventArgs e)
        {
            try
            {
                Object objData = richTextRxMessage.Text;
                byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
                if (m_clientSocket != null)
                {
                    m_clientSocket.Send(byData);
                }
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            if (m_clientSocket != null)
            {
                m_clientSocket.Close();
                m_clientSocket = null;
            }
            Close();
        }
    }
}


Comments