/// <summary>
        /// Inicia o recebimento de dados assincrono.
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public override CommunicationResult BeginReceive(Action <byte[], System.Net.IPEndPoint> action)
        {
            CommunicationResult success = CommunicationResult.Success;

            lock (this._lockObject)
            {
                CommunicationResult result2 = Bind(LocalEndPoint);
                if (result2 == 0)
                {
                    return(result2);
                }
                _isReceiving    = true;
                _actionCallBack = action;
                try
                {
                    _udpClient.BeginReceive(new AsyncCallback(UdpClientReceive), _udpClient);
                }
                catch (SocketException exception)
                {
                    success = new CommunicationResult(exception.ErrorCode);
                }
                catch (InvalidOperationException)
                {
                    success = CommunicationResult.Closed;
                }
            }
            return(HandleResult(success));
        }
        /// <summary>
        /// Despacha os dados para o endPoint informado.
        /// </summary>
        /// <param name="data"></param>
        /// <param name="size"></param>
        /// <param name="remoteEndPoint"></param>
        /// <returns></returns>
        private CommunicationResult Dispatch(byte[] data, int size, System.Net.IPEndPoint remoteEndPoint)
        {
            CommunicationResult success = CommunicationResult.Success;

            lock (_lockObject)
            {
                CommunicationResult result2 = Bind(LocalEndPoint);
                if (result2 == 0)
                {
                    return(result2);
                }
                try
                {
                    _udpClient.Send(data, size, remoteEndPoint);
                }
                catch (ArgumentNullException)
                {
                    success = CommunicationResult.SendFailed;
                }
                catch (ObjectDisposedException)
                {
                    success = CommunicationResult.Closed;
                }
                catch (InvalidOperationException)
                {
                    success = CommunicationResult.SendFailed;
                }
                catch (SocketException exception)
                {
                    success = new CommunicationResult(exception.ErrorCode);
                }
            }
            return(HandleResult(success));
        }
        /// <summary>
        /// Vincula o EndPoint.
        /// </summary>
        /// <param name="localEndPoint"></param>
        /// <returns></returns>
        private CommunicationResult Bind(System.Net.IPEndPoint localEndPoint)
        {
            CommunicationResult success = CommunicationResult.Success;

            lock (this._lockObject)
            {
                if (_udpClient != null)
                {
                    if (!this._needBinding)
                    {
                        return(CommunicationResult.Success);
                    }
                    _udpClient.Close();
                    _udpClient = null;
                }
                try
                {
                    _udpClient   = new UdpClient(localEndPoint);
                    _needBinding = false;
                }
                catch (SocketException exception)
                {
                    _udpClient = new UdpClient();
                    success    = new CommunicationResult(exception.ErrorCode);
                }
            }
            return(HandleResult(success));
        }
 /// <summary>
 /// Recebe os dados de forma assincrona.
 /// </summary>
 /// <param name="receiveAction"></param>
 /// <param name="timeoutAction"></param>
 /// <param name="expectResponse"></param>
 /// <returns></returns>
 public override CommunicationResult ReceiveAsync(Action <byte[], System.Net.IPEndPoint> receiveAction, Action <System.Net.IPEndPoint> timeoutAction, bool expectResponse)
 {
     System.Threading.ThreadStart start = delegate {
         byte[] data = null;
         CommunicationResult result = CommunicationResult.ReceiveFailed;
         int tcpTimeout             = this.TcpTimeout;
         while (true)
         {
             lock (_tcpLock)
             {
                 if (Stream == null)
                 {
                     result = CommunicationResult.Closed;
                     break;
                 }
                 if (this.DataAvailable)
                 {
                     result = this.ReceiveBase(out data);
                     break;
                 }
             }
             if (tcpTimeout <= 0)
             {
                 result = CommunicationResult.Timeout;
                 break;
             }
             System.Threading.Thread.Sleep(Math.Min(10, tcpTimeout));
             tcpTimeout = Math.Max(tcpTimeout - 10, 0);
         }
         if (result == 0)
         {
             if ((result == CommunicationResult.Timeout) || (result == 0x274c))
             {
                 timeoutAction(RemoteEndPoint);
             }
             if (expectResponse)
             {
                 HandleResult(result);
             }
         }
         else
         {
             receiveAction(data, this.RemoteEndPoint);
         }
     };
     try
     {
         new System.Threading.Thread(start).Start();
     }
     catch (ArgumentNullException)
     {
         return(this.HandleResult(CommunicationResult.ReceiveFailed));
     }
     catch (System.Threading.ThreadStateException)
     {
         return(this.HandleResult(CommunicationResult.ReceiveFailed));
     }
     return(CommunicationResult.Success);
 }
 /// <summary>
 /// Inicia o processo assincrono para recebimento dos dados.
 /// </summary>
 /// <param name="action"></param>
 /// <returns></returns>
 public CommunicationResult BeginReceive(Action <byte[]> action)
 {
     try
     {
         lock (_actionLock)
             _actionCallBack = action;
         LogAccessor.Log.Verbose("<TCP> Begin Receive");
         this.ReadBuffer();
         CommunicationResult success = CommunicationResult.Success;
         lock (_tcpLock)
         {
             if (_receiving || ((_readResult != null) && !_readResult.IsCompleted))
             {
                 LogAccessor.Log.Verbose("<TCP> Already Receiving=>Skip Begin Receive");
             }
             else if (this.Stream == null)
             {
                 success = CommunicationResult.Closed;
                 LogAccessor.Log.Verbose("<TCP> Connection is Closed=>Skip Begin Receive");
             }
             else
             {
                 byte[] data = new byte[1024];
                 TcpCommunicationState state = new TcpCommunicationState(data);
                 _receiving  = true;
                 _readResult = Stream.BeginRead(data, 0, data.Length, new AsyncCallback(TcpStreamReceived), state);
             }
         }
         return(HandleResult(success));
     }
     catch (System.IO.IOException)
     {
         _receiving = false;
         return(this.HandleResult(CommunicationResult.Closed));
     }
     catch (ObjectDisposedException)
     {
         _receiving = false;
         return(HandleResult(CommunicationResult.Closed));
     }
     catch (ArgumentException)
     {
         _receiving = false;
     }
     catch (NotSupportedException)
     {
         _receiving = false;
         return(HandleResult(CommunicationResult.Closed));
     }
     catch (InvalidOperationException)
     {
         _receiving = false;
         return(HandleResult(CommunicationResult.Closed));
     }
     return(HandleResult(CommunicationResult.ReceiveFailed));
 }
        /// <summary>
        /// Envia os dados.
        /// </summary>
        /// <param name="data">Dados que serão enviados.</param>
        /// <param name="size">Tamanho dos dados.</param>
        /// <returns></returns>
        public override CommunicationResult Send(byte[] data, int size)
        {
            CommunicationResult success = CommunicationResult.Success;

            try
            {
                lock (_tcpLock)
                {
                    if (Stream != null)
                    {
                        Stream.Write(data, 0, size);
                        Stream.Flush();
                    }
                    else
                    {
                        success = CommunicationResult.Closed;
                    }
                }
                if ((success != 0) && (base.RemoteEndPoint != null))
                {
                    LogAccessor.Log.Verbose("<TCP>Sent to [{0}]: {1}", base.RemoteEndPoint.ToString(), BinaryTransformer.GetString(data, 0, size));
                }
            }
            catch (ArgumentNullException)
            {
                return(this.HandleResult(CommunicationResult.SendFailed));
            }
            catch (ArgumentOutOfRangeException)
            {
                return(this.HandleResult(CommunicationResult.SendFailed));
            }
            catch (ArgumentException)
            {
                return(this.HandleResult(CommunicationResult.SendFailed));
            }
            catch (NotSupportedException)
            {
                return(this.HandleResult(CommunicationResult.SendFailed));
            }
            catch (ObjectDisposedException)
            {
                return(this.HandleResult(CommunicationResult.Closed));
            }
            catch (System.IO.IOException exception)
            {
                var innerException = exception.InnerException as System.Net.Sockets.SocketException;
                if (innerException != null)
                {
                    return(HandleResult(new CommunicationResult(innerException.ErrorCode)));
                }
                return(HandleResult(CommunicationResult.Closed));
            }
            return(HandleResult(success));
        }
 /// <summary>
 /// Tranta o resultado.
 /// </summary>
 /// <param name="result"></param>
 /// <returns></returns>
 private CommunicationResult HandleResult(CommunicationResult result)
 {
     if (result == 0)
     {
         this.LastError = result;
         LogAccessor.Log.Info(result.GetDebugInfo());
         if (ErrorOccurred != null)
         {
             ErrorOccurred(this, new CommunicationErrorEventArgs(CommunicationProtocol.Tcp, result));
         }
     }
     return(result);
 }
 /// <summary>
 /// Trata o resultado da comunicação.
 /// </summary>
 /// <param name="result"></param>
 /// <returns></returns>
 private CommunicationResult HandleResult(CommunicationResult result)
 {
     if (result == 0)
     {
         if ((result != CommunicationResult.Closed) || this._isReceiving)
         {
             LogAccessor.Log.Info(result.GetDebugInfo());
         }
         if (ErrorOccurred != null)
         {
             ErrorOccurred(this, new CommunicationErrorEventArgs(CommunicationProtocol.Udp, result));
         }
     }
     return(result);
 }
        /// <summary>
        /// Recebe os dados.
        /// </summary>
        /// <param name="data">Buffer dos dados recebidos.</param>
        /// <param name="expectedSize">Tamanho esperado.</param>
        /// <returns></returns>
        public CommunicationResult Receive(out byte[] data, int expectedSize)
        {
            CommunicationResult receiveFailed = CommunicationResult.ReceiveFailed;

            lock (_tcpLock)
                receiveFailed = _reader.ReadStream(this.Stream, out data, expectedSize);
            if (receiveFailed == 0)
            {
                return(HandleResult(receiveFailed));
            }
            if (base.RemoteEndPoint != null)
            {
                LogAccessor.Log.Verbose("<TCP>Received from [{0}]: {1}", base.RemoteEndPoint.ToString(), BinaryTransformer.GetString(data, 0, data.Length));
            }
            return(receiveFailed);
        }
        /// <summary>
        /// Construtor estático.
        /// </summary>
        static CommunicationResult()
        {
            Success       = new CommunicationResult(0);
            Closed        = new CommunicationResult(2);
            AlreadyOpen   = new CommunicationResult(1);
            OpenFailed    = new CommunicationResult(3);
            Timeout       = new CommunicationResult(4);
            SendFailed    = new CommunicationResult(5);
            ReceiveFailed = new CommunicationResult(6);
            AddressUsed   = new CommunicationResult(0x2740);
            Dictionary <int, string> dictionary = new Dictionary <int, string>();

            dictionary.Add(4, Properties.Resources.CommunicationReader_FormatErrorTimeout);
            dictionary.Add(0x1c4, Properties.Resources.CommunicationReader_FormatErrorFtpDiskFull);
            dictionary.Add(0x228, Properties.Resources.CommunicationReader_FormatErrorFtpDiskFull);
            dictionary.Add(0x274c, Properties.Resources.CommunicationReader_FormatErrorTimeout);
            dictionary.Add(0x3f0, Properties.Resources.CommunicationReader_FormatErrorNoOpFailed);
            _resultDictionary = dictionary;
        }
        /// <summary>
        /// Método base para recebimento dos dados.
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private CommunicationResult ReceiveBase(out byte[] data)
        {
            CommunicationResult receiveFailed = CommunicationResult.ReceiveFailed;

            data = null;
            try
            {
                lock (_tcpLock)
                {
                    if (_tcpClient == null)
                    {
                        receiveFailed = CommunicationResult.Closed;
                    }
                    else
                    {
                        _tcpClient.Client.Blocking = true;
                        receiveFailed = _reader.ReadStream(this.Stream, out data);
                    }
                }
            }
            catch (System.Net.Sockets.SocketException exception)
            {
                receiveFailed = new CommunicationResult(exception.ErrorCode);
            }
            catch (ObjectDisposedException)
            {
                receiveFailed = CommunicationResult.Closed;
            }
            if ((receiveFailed != 0) && (base.RemoteEndPoint != null) && data != null)
            {
                LogAccessor.Log.Verbose("<TCP>Received from [{0}]: {1}", new object[] {
                    base.RemoteEndPoint.ToString(),
                    BinaryTransformer.GetString(data, 0, data.Length)
                });
            }
            return(receiveFailed);
        }
        /// <summary>
        /// Abrea a comunicação.
        /// </summary>
        /// <returns></returns>
        public override CommunicationResult Open()
        {
            CommunicationResult result = CommunicationResult.OpenFailed;

            try
            {
                lock (_tcpLock)
                {
                    LastError = CommunicationResult.Success;
                    if ((_tcpClient == null) || (_tcpClient.Client == null))
                    {
                        _tcpClient  = new System.Net.Sockets.TcpClient();
                        _receiving  = false;
                        _readResult = null;
                    }
                    AsyncCallback callback2 = null;
                    using (var resetEvent = new System.Threading.ManualResetEvent(false))
                    {
                        if (callback2 == null)
                        {
                            callback2 = delegate(IAsyncResult asyncResult) {
                                result = TryOpen(asyncResult);
                                try
                                {
                                    resetEvent.Set();
                                }
                                catch (NullReferenceException)
                                {
                                }
                                catch (ObjectDisposedException)
                                {
                                }
                            };
                        }
                        AsyncCallback requestCallback = callback2;
                        if ((_tcpClient == null) || (_tcpClient.Client == null))
                        {
                            return(CommunicationResult.OpenFailed);
                        }
                        _tcpClient.BeginConnect(RemoteEndPoint.Address, base.RemoteEndPoint.Port, requestCallback, _tcpClient);
                        if (!resetEvent.WaitOne(TcpTimeout, true))
                        {
                            try
                            {
                                _tcpClient.Close();
                            }
                            finally
                            {
                                result = CommunicationResult.OpenFailed;
                            }
                        }
                    }
                }
            }
            catch (ArgumentNullException)
            {
                result = CommunicationResult.OpenFailed;
            }
            catch (ArgumentOutOfRangeException)
            {
                result = CommunicationResult.OpenFailed;
            }
            catch (ObjectDisposedException)
            {
                result = CommunicationResult.OpenFailed;
            }
            catch (System.Net.Sockets.SocketException exception)
            {
                if (exception.ErrorCode == 0x2748)
                {
                    result = CommunicationResult.AlreadyOpen;
                }
                else
                {
                    result = new CommunicationResult(exception.ErrorCode);
                }
            }
            catch (InvalidOperationException)
            {
                result = CommunicationResult.OpenFailed;
            }
            catch (System.Security.SecurityException)
            {
                result = CommunicationResult.OpenFailed;
            }
            catch (System.Threading.AbandonedMutexException)
            {
                result = CommunicationResult.OpenFailed;
            }
            finally
            {
                if ((result.ErrorCode == 1) && !this.IsOpen)
                {
                    result = CommunicationResult.OpenFailed;
                }
                if ((result != 0) || (result.ErrorCode == 1))
                {
                    try
                    {
                        _tcpStream = _tcpClient.GetStream();
                        if (_tcpStream != null)
                        {
                            _tcpStream.WriteTimeout = TcpTimeout;
                            _tcpStream.ReadTimeout  = TcpTimeout;
                        }
                    }
                    catch (ObjectDisposedException)
                    {
                        result = CommunicationResult.Closed;
                    }
                    catch (InvalidOperationException)
                    {
                        result = CommunicationResult.Closed;
                    }
                }
                else
                {
                    _tcpClient = null;
                    HandleResult(result);
                }
            }
            return(result);
        }
        /// <summary>
        /// Método acionado quando dados forem recebidos da stream da conexão.
        /// </summary>
        /// <param name="result"></param>
        private void TcpStreamReceived(IAsyncResult result)
        {
            CommunicationResult success = CommunicationResult.Success;

            try
            {
                int length = 0;
                try
                {
                    lock (_tcpLock)
                    {
                        _receiving = false;
                        if (Stream == null)
                        {
                            return;
                        }
                        length = Stream.EndRead(result);
                        if (length == 0)
                        {
                            if (base.RemoteEndPoint != null)
                            {
                                LogAccessor.Log.Verbose("<TCP>Connection closed by remote host [{0}]", new object[] {
                                    base.RemoteEndPoint.ToString()
                                });
                            }
                            success = CommunicationResult.Closed;
                            return;
                        }
                        TcpCommunicationState asyncState = (TcpCommunicationState)result.AsyncState;
                        if (_actionCallBack != null)
                        {
                            byte[] data = asyncState.GetData();
                            LogAccessor.Log.Verbose("<TCP> Packet: {0}", new object[] {
                                BinaryTransformer.GetString(data, 0, length, Encoding.ASCII)
                            });
                            success = _reader.RegisterBuffer(data, length);
                        }
                    }
                }
                catch (ArgumentNullException)
                {
                    success = CommunicationResult.ReceiveFailed;
                    return;
                }
                catch (ArgumentException)
                {
                    success = CommunicationResult.ReceiveFailed;
                    return;
                }
                catch (System.IO.IOException)
                {
                    BeginReceive(_actionCallBack);
                    return;
                }
                catch (ObjectDisposedException)
                {
                    return;
                }
                if (success != 0)
                {
                    ReadBuffer();
                    BeginReceive(_actionCallBack);
                }
            }
            finally
            {
                HandleResult(success);
            }
        }
        /// <summary>
        /// Método acionado quando for recebido uma mensagem do cliente UDP.
        /// </summary>
        /// <param name="result"></param>
        private void UdpClientReceive(IAsyncResult result)
        {
            CommunicationResult success = CommunicationResult.Success;

            try
            {
                byte[] buffer;
                var    remoteEP = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0);
                lock (_lockObject)
                {
                    if (base.RemoteEndPoint != null)
                    {
                        remoteEP = base.RemoteEndPoint;
                    }
                    buffer = _udpClient.EndReceive(result, ref remoteEP);
                }
                _actionCallBack(buffer, remoteEP);
                lock (_lockObject)
                {
                    if (_isReceiving)
                    {
                        if (_udpClient == null)
                        {
                            success = CommunicationResult.Closed;
                        }
                        else
                        {
                            _udpClient.BeginReceive(new AsyncCallback(UdpClientReceive), _udpClient);
                        }
                    }
                }
            }
            catch (ArgumentNullException)
            {
                success = CommunicationResult.Closed;
            }
            catch (ArgumentException)
            {
                success = CommunicationResult.Closed;
            }
            catch (ObjectDisposedException)
            {
                success = CommunicationResult.Closed;
            }
            catch (InvalidOperationException)
            {
                success = CommunicationResult.Closed;
            }
            catch (SocketException exception)
            {
                success = new CommunicationResult(exception.ErrorCode);
            }
            catch (NullReferenceException)
            {
                success = CommunicationResult.Closed;
            }
            finally
            {
                HandleResult(success);
            }
        }
 /// <summary>
 /// Lê a stream.
 /// </summary>
 /// <param name="stream"></param>
 /// <param name="data"></param>
 /// <param name="expectedSize"></param>
 /// <returns></returns>
 public CommunicationResult ReadStream(Stream stream, out byte[] data, int expectedSize)
 {
     data = null;
     try
     {
         if (stream == null)
         {
             return(CommunicationResult.Closed);
         }
         if (ReadBuffer(out data, expectedSize))
         {
             return(CommunicationResult.Success);
         }
         int    bufferSize = 0;
         byte[] buffer     = new byte[1024];
         var    stopwatch  = new System.Diagnostics.Stopwatch();
         stopwatch.Start();
         while ((bufferSize = stream.Read(buffer, 0, 0x400)) != -1)
         {
             if (bufferSize <= 0)
             {
                 if (stopwatch.Elapsed.TotalMilliseconds >= stream.ReadTimeout)
                 {
                     LogAccessor.Log.Verbose("<COMMUNICATION READER> Reading Timeout => Exiting Loop");
                     return(CommunicationResult.Timeout);
                 }
             }
             else
             {
                 CommunicationResult result = RegisterBuffer(buffer, bufferSize);
                 if (result == 0)
                 {
                     return(result);
                 }
                 if (ReadBuffer(out data, expectedSize))
                 {
                     return(CommunicationResult.Success);
                 }
             }
         }
     }
     catch (ArgumentNullException)
     {
         return(CommunicationResult.ReceiveFailed);
     }
     catch (ArgumentOutOfRangeException)
     {
         return(CommunicationResult.ReceiveFailed);
     }
     catch (UnauthorizedAccessException)
     {
         return(CommunicationResult.Closed);
     }
     catch (ObjectDisposedException)
     {
         return(CommunicationResult.Closed);
     }
     catch (IOException exception)
     {
         var innerException = exception.InnerException as System.Net.Sockets.SocketException;
         if (innerException != null)
         {
             return(new CommunicationResult(innerException.ErrorCode));
         }
         return(CommunicationResult.Timeout);
     }
     catch (NotSupportedException)
     {
         return(CommunicationResult.Closed);
     }
     catch (System.Net.Sockets.SocketException exception3)
     {
         return(new CommunicationResult(exception3.ErrorCode));
     }
     catch (TimeoutException)
     {
         return(CommunicationResult.Timeout);
     }
     return(CommunicationResult.ReceiveFailed);
 }
Beispiel #16
0
 /// <summary>
 /// Construtor padrão.
 /// </summary>
 /// <param name="protocol"></param>
 /// <param name="result"></param>
 public CommunicationErrorEventArgs(CommunicationProtocol protocol, CommunicationResult result)
 {
     Protocol = protocol;
     Detail   = result;
 }