Esempio n. 1
0
 protected override void ThreadTick()
 {
     try
     {
         if (hasCreatedSocket == true)
         {
             Send();
             lock (packetsReceived)
             {
                 if (packetsReceived.Count > 0)
                 {
                     OnPacketsReceived?.Invoke(this, packetsReceived);
                     packetsReceived.Clear();
                 }
             }
             if (isWaitingToListen)
             {
                 BeginReceive();
                 isWaitingToListen = false;
             }
         }
         else if (CanAttemptToConnectNow())
         {
             CreateSocket();
         }
     }
     catch (Exception e)
     {
         Console.Error.WriteLine(e);
         OnThreadException?.Invoke(this, e);
     }
 }
Esempio n. 2
0
 private void SpinAwait()
 {
     while (!disposing)
     {
         try
         {
             WaitForAvailableThread();
             if (disposing)
             {
                 return;
             }
             if (PendingTasks.Count > 0)
             {
                 AbortableTask action = PendingTasks[0];
                 try
                 {
                     action.Task.Start(TaskFactory.Scheduler);
                     Tasks.Add(action);
                 }
                 catch (System.Exception ex1)
                 {
                     if (OnThreadException != null)
                     {
                         OnThreadException.Invoke(this, ex1, action);
                     }
                     else
                     {
                         throw;
                     }
                 }
                 PendingTasks.Remove(action);
             }
         }
         catch (System.Exception ex0)
         {
             if (OnThreadException != null)
             {
                 OnThreadException.Invoke(this, ex0);
             }
             else
             {
                 throw;
             }
         }
         System.Threading.Thread.Sleep(20);
     }
 }
Esempio n. 3
0
 private void BeginReceive()
 {
     try
     {
         GrowReadBufferIfFull();
         socketConnection.BeginReceive(readBuffer, readBufferOffset, readBuffer.Length - readBufferOffset, 0,
                                       new AsyncCallback(ReceiveCallback), this);
     }
     catch (SocketException)
     {
         FailSocket();
     }
     catch (Exception e)
     {
         Console.WriteLine(e.ToString());
         OnThreadException?.Invoke(this, e);
     }
 }
Esempio n. 4
0
        /////////////////////////////////////////////////////////////////////
        // THREAD EXCEPTIONS
        /////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Capture thrown exceptions and trigger the OnInternalException event.
        /// </summary>
        /// <param name="func">The action to execute. Exceptions raised within will be caught and redirected to the OnThreadException event.</param>
        /// <returns>True if an exception was caught.</returns>
        protected bool CaptureException(Action func)
        {
            if (func == null)
            {
                throw new ArgumentNullException("func");
            }

            try
            {
                func();
            }
            catch (Exception exc)
            {
                OnThreadException?.Invoke(this, new ThreadException(exc));
                return(true);
            }
            return(false);
        }
Esempio n. 5
0
        private void ConnectCallback(IAsyncResult ar)
        {
            // Have we already freed these up?
            if (socketConnection == null)
            {
                return;
            }

            try
            {
                socketConnection.EndConnect(ar);

                if (socketConnection.IsBound == false)
                {
                    throw new SocketException();
                }
                else
                {
                    Console.WriteLine("Connected to {0}:{1}", settings.ipAddress, settings.port);
                    hasCreatedSocket = true;
                    OnConnect?.Invoke(this);
                    BeginReceive();
                }
            }
            catch (SocketException e)
            {
                // We most likely failed to establish the socket connection
                Console.WriteLine(e.ToString());
                RecordFailedConnectAttempt();
                Console.WriteLine("Failed to connect to {0}:{1}, {2} retries remaining",
                                  settings.ipAddress, settings.port, retryAttemptsLeft);
            }
            catch (Exception e)
            {
                // An unexpected exception occurred
                Console.WriteLine(e.ToString());
                RecordFailedConnectAttempt();
                OnThreadException?.Invoke(this, e);
            }
            finally
            {
                isCreatingSocket = false;
            }
        }
Esempio n. 6
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            // Have we already freed these up?
            if (socketConnection == null)
            {
                return;
            }

            int bytesRead = 0;

            try
            {
                bytesRead = socketConnection.EndReceive(ar);
                if (bytesRead > 0)
                {
#if DEBUG_NETWORK_STREAM
                    numReceives++;
                    Console.WriteLine("Received {2}x for {0} bytes, giving {1} bytes unparsed", bytesRead, readBufferOffset + bytesRead, numReceives);
#endif
                    IncommingBytesToPackets(readBuffer, readBufferOffset + bytesRead);

                    // Try to grab more immediately
                    BeginReceive();
                }
                else
                {
                    // We didn't get anything this time round, so wait a little bit
                    isWaitingToListen = true;
                }
            }
            catch (SocketException)
            {
                FailSocket();
                return;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                OnThreadException?.Invoke(this, e);
            }
            //ThreadPool.QueueUserWorkItem(ThreadProc, this);
        }
Esempio n. 7
0
        private void SendRecursive(BasePacket[] packetList, int retry = 0)
        {
            try
            {
                socketConnection.Send(memoryStream.ToArray(), (int)memoryStream.Position, 0);
            }
            catch (SocketException)
            {
                /*#if DEBUG_NETWORK_PACKETS
                 *              Console.WriteLine("Failed to send packet {0}", packet);
                 #endif*/

                lock (packetsToSend)
                {
                    foreach (var bp in packetList)
                    {
                        packetsToSend.Enqueue(bp);
                    }
                }
                retry++;
                if (retry > settings.maxRetryAttempts)
                {
                    FailSocket();
                }
                else
                {
                    SendRecursive(packetList, retry);
                }
            }
            catch (Exception e)
            {
                /*
                 #if DEBUG_NETWORK_PACKETS
                 * Console.WriteLine("Failed to send packet {0} so skipping, root exception: {1}", packet, e.ToString());
                 #endif
                 */
                OnThreadException?.Invoke(this, e);
            }
        }