Socket Server and Client

The code was originally written Ashish Dhar then modified by me.

 

 

 

Server

 

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using System.Net;

using System.Net.Sockets;

 

namespace SocketServer

{

     

      public partial class Form1 : Form

      {

            public  AsyncCallback pfnWorkerCallBack ;

            public  Socket m_socListener;

            public  Socket m_socWorker;

 

            public Form1()

            {

                  InitializeComponent();

            }

 

 

 

            private void cmdListen_Click(object sender, System.EventArgs e)

            {

                  try

                  {

                        //create the listening socket...

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

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

                        //bind to local IP Address...

                        m_socListener.Bind( ipLocal );

                        //start listening...

                        m_socListener.Listen (4);

                        // create the call back for any client connections...

                        m_socListener.BeginAccept(new AsyncCallback ( OnClientConnect ),null);

                        cmdListen.Enabled = false;

 

                  }

                  catch(Exception se)

                  {

                        MessageBox.Show ( se.Message );

                  }

            }

 

            public void OnClientConnect(IAsyncResult asyn)

            {

                  try

                  {

                        m_socWorker = m_socListener.EndAccept (asyn);

                         

                        WaitForData(m_socWorker);

                  }

                  catch(Exception se)

                  {

                        MessageBox.Show ( se.Message );

                  }

                 

            }

            public class CSocketPacket

            {

                  public System.Net.Sockets.Socket thisSocket;

                  public byte[] dataBuffer = new byte[1];

            }

 

            public void WaitForData(System.Net.Sockets.Socket soc)

            {

                  try

                  {

                        if  ( pfnWorkerCallBack == null )

                        {

                             pfnWorkerCallBack = new AsyncCallback(OnDataReceived);

                        }

                        CSocketPacket theSocPkt = new CSocketPacket ();

                        theSocPkt.thisSocket = soc;

                        // now start to listen for any data...

                        soc.BeginReceive (theSocPkt.dataBuffer ,0,theSocPkt.dataBuffer.Length

                       ,SocketFlags.None,pfnWorkerCallBack,theSocPkt);

                  }

                  catch(Exception se)

                  {

                        MessageBox.Show(se.Message );

                  }

 

            }

 

            public  void OnDataReceived(IAsyncResult asyn)

            {

                  try

                  {

                        CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState ;

                        //end receive...

                        int iRx  = 0 ;

                        iRx = theSockId.thisSocket.EndReceive(asyn);

                        char[] chars = new char[iRx +  1];

                        System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();

                        int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);

                        System.String szData = new System.String(chars);

               

                        //the function below is equivalent

                       //to txtDataRx.Text = txtDataRx.Text + szData;

                       //which can’t be used in another thread

                        UpdadeText(szData);

                        WaitForData(m_socWorker);

                  }

                  catch (ObjectDisposedException)

                  {

                        System.Diagnostics.Debugger.Log(0,"1","\nOnDataReceived: Socket has been closed\n");

                  }

                  catch(SocketException se)

                  {

                        MessageBox.Show(se.Message);

                  }

            }

 

            private void button1_Click(object sender, System.EventArgs e)

            {

                  try

                  {

                        Object objData = txtDataTx.Text;

                        byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString ());

                        m_socWorker.Send (byData);

                  }

                  catch(SocketException se)

                  {

                        MessageBox.Show (se.Message );

                  }

            }

 

 

        //the code below is needed to access the textbox from another thread than it was created by

        delegate void UpdateTextD(string s);

 

        void UpdadeText(string s)

        {

            txtDataRx.Invoke(new UpdateTextD(sD), new object[] {s});

        }

 

        void sD(string s)

        {

            txtDataRx.Text += s;

        }

 

      }

}

 

 

 

 

Client

 

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using System.Net.Sockets ;

 

namespace Project01

{

      public partial class Form1 : Form

      {

           

            Socket m_socClient;

 

            public Form1()

            {

                  InitializeComponent();

            }

 

            private void cmdConnect_Click(object sender, System.EventArgs e)

            {

                  try

                  {

                        //create a new client socket ...

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

                        String szIPSelected  = txtIPAddress.Text;

                        String szPort = txtPort.Text;

                        int  alPort = System.Convert.ToInt16 (szPort,10);

                 

                        System.Net.IPAddress    remoteIPAddress   = System.Net.IPAddress.Parse(szIPSelected);

                        System.Net.IPEndPoint   remoteEndPoint = new System.Net.IPEndPoint(remoteIPAddress, alPort);

                        m_socClient.Connect(remoteEndPoint);

                        String szData  = "Hello There";

                        byte[] byData = System.Text.Encoding.ASCII.GetBytes(szData);

                        m_socClient.Send(byData);

 

                  }

                  catch (Exception se)

                  {

                        MessageBox.Show ( se.Message );

                  }

            }

             

 

            private void cmdSendData_Click(object sender, System.EventArgs e)

            {

                  try

                  {

                        Object objData = txtData.Text;

                        byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString ());

                        m_socClient.Send (byData);

                  }

                  catch(Exception se)

                  {

                        MessageBox.Show (se.Message );

                  }

            }

 

            private void cmdReceiveData_Click(object sender, System.EventArgs e)

            {

                  try

                  {

                        byte [] buffer = new byte[1024];

                        int iRx = m_socClient.Receive (buffer);

                        char[] chars = new char[iRx];

 

                        System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();

                        int charLen = d.GetChars(buffer, 0, iRx, chars, 0);

                        System.String szData = new System.String(chars);

                        txtDataRx.Text = szData;

                  }

                  catch(Exception se)

                  {

                        MessageBox.Show (se.Message );

                  }

            }

 

            private void cmdClose_Click(object sender, System.EventArgs e)

            {

                  m_socClient.Close ();

            }

 

           

 

      }

}

 

 

source