/// <summary>
 /// Used to wait for data on the socket asynchonously
 /// </summary>
 public void WaitForData()
 {
     if (fncCallBack == null)
     {
         fncCallBack = new AsyncCallback(WaitForDataCallback);
     }
     socPak          = new SocketPack(1024);
     socPak.socket   = rcvSocket;
     dataAsyncResult = rcvSocket.BeginReceiveFrom(socPak.dataBuffer,
                                                  0,
                                                  socPak.dataBuffer.Length,
                                                  SocketFlags.None,
                                                  ref this.rcvEP,
                                                  fncCallBack,
                                                  socPak);
 }
 private void WaitForDataCallback(IAsyncResult asyn)
 {
     try
     {
         theSockId = (SocketPack)asyn.AsyncState;                         //We catch the asyncronous answer
         int iRx = theSockId.socket.EndReceiveFrom(asyn, ref this.rcvEP); //And finish it
         if (iRx < 1)                                                     //If less than one, might mean we are receiving "garbage"
         {                                                                //So we start counting for possible errors
             if (this.errCounter.Inc() == errCounter.Maximum)             //If it reaches the maximum possible consecutive errors
             {
                 //Totally shutdown and close the socket and trigger the SocketClosed Event
                 theSockId.socket.Shutdown(System.Net.Sockets.SocketShutdown.Both);
                 theSockId.socket.Close();
                 OnSocketClosed(theSockId);
                 this.errCounter.Reset();                                //Don't forget to reset error counter
             }
         }
         else
         {
             this.errCounter.Reset();                                            //Reset error counter of all possible garbage received
             SocketPack callBackPack = new SocketPack(iRx);                      //repack the data that arrived into a new SocketPack
             callBackPack.socket = theSockId.socket;
             for (int counter = 0; counter < iRx; counter++)
             {
                 callBackPack.dataBuffer[counter] = theSockId.dataBuffer[counter];
             }
             OnDataReceived(callBackPack);
         }
     }
     catch (System.ObjectDisposedException)
     {       }
     catch (Exception)
     {
         _Connected = false;
         OnSocketClosed(theSockId);
     }
 }
 protected virtual void OnSocketClosed(SocketPack socData)
 {
     SocketClosed(this, socData);
 }
 protected virtual void OnDataReceived(SocketPack socData)
 {
     DataReceived(this, socData);
 }