Beispiel #1
0
 /// <summary>
 /// 断开连接
 /// </summary>
 public void Disconnect()
 {
     if (isConnect)
     {
         OnClosed();
         SyncCall.Add(() =>
         {
             if (OnDisconnect == null)
             {
                 return;
             }
             OnDisconnect(this, new EventArgs());
         });
         try
         {
             this._socket.Shutdown(SocketShutdown.Both);
         }
         catch (Exception e)
         {
             Debuger.Log(e.ToString());
         }
         isConnect = false;
         if (this.ProcessThread != null && this.ProcessThread.IsAlive)
         {
             SendEvent.Set();
             ProcessThread.Join(1000);
         }
         Close();
     }
 }
        private void ReceiveCallback(IAsyncResult asyncResult)
        {
            var operation = (IOperation)asyncResult.AsyncState;

            try
            {
                var bytesRead = _networkStream.EndRead(asyncResult);
                if (bytesRead == 0)
                {
                    SendEvent.Set();
                    return;
                }
                operation.Read(operation.Buffer, 0, bytesRead);
                BufferManager.ReturnBuffer(operation.Buffer);

                if (operation.LengthReceived < operation.TotalLength)
                {
                    operation.Buffer = BufferManager.TakeBuffer(512);
                    _networkStream.BeginRead(operation.Buffer, 0, operation.Buffer.Length, ReceiveCallback, operation);
                }
                else
                {
                    SendEvent.Set();
                }
            }
            catch (Exception e)
            {
                HandleException(e, operation);
            }
        }
        public void Dispose()
        {
            if (isDisposed_)
            {
                return;
            }

            lock (ThreadLock) {
                if (sendingTaskAwaiter_ != null)
                {
                    ThreadCancellationTokenSource.Cancel();
                    SendEvent.Set();
                    sendingTaskAwaiter_.Value.GetAwaiter().OnCompleted(() => {
                        SendEvent.Dispose();
                        ThreadCancellationTokenSource.Dispose();
                    });
                }
                else
                {
                    SendEvent.Dispose();
                    ThreadCancellationTokenSource.Dispose();
                }
            }
            DataSender.Dispose();

            GC.SuppressFinalize(this);
            isDisposed_ = true;
        }
Beispiel #4
0
        public int PingDurtion = 3000; //

        /// <summary>
        /// 发送一个消息
        /// </summary>
        /// <param name="message"></param>
        public void SendMessage(Message message)
        {
            BufferMessage.AddMessage(message);
            if (UsedThread)
            {
                SendEvent.Set();
            }
        }
Beispiel #5
0
 /// <summary>
 /// 接收到消息
 /// </summary>
 /// <param name="message"></param>
 public virtual void OnReceived(Message message)
 {
     if (message.Class == MessageClass.Ping)
     {
         #region Ping
         var  tickNow  = DateTime.Now.Ticks;
         long tickSend = 0;
         using (var mem = new MemoryStream(message.Content))
         {
             using (var br = new BinaryReader(mem))
             {
                 tickSend = br.ReadInt64();
             }
         }
         Delay = (tickNow - tickSend);
         SyncCall.Add(() =>
         {
             if (OnPingCompleted != null)
             {
                 OnPingCompleted(this, new PingCompletedArgs {
                     DelayTicks = Delay
                 });
             }
         });
         #endregion
     }
     else if (message.Class == MessageClass.Package)
     {
         var bufferPackage = MessageBufferPackage.ParseFromMessage(message);
         foreach (var m in bufferPackage.Messages)
         {
             OnReceived(m);
         }
     }
     else if (message.Class == MessageClass.Close)
     {
         this.Disconnect();
     }
     else
     {
         ReceivedBufferMessage(message);
     }
     if (UsedThread)
     {
         SendEvent.Set();
     }
 }
Beispiel #6
0
        private void ReceiveCallback(IAsyncResult asyncResult)
        {
            var state = (SocketAsyncState)asyncResult.AsyncState;

            try
            {
                var bytesRecieved = _sslStream.EndRead(asyncResult);
                state.BytesReceived += bytesRecieved;
                if (state.BytesReceived == 0)
                {
                    BufferManager.ReturnBuffer(state.Buffer);
                    SendEvent.Set();
                    return;
                }
                if (state.BodyLength == 0)
                {
                    state.BodyLength = Converter.ToInt32(state.Buffer, HeaderIndexFor.Body);
                }

                state.Data.Write(state.Buffer, 0, bytesRecieved);

                if (state.BytesReceived < state.BodyLength + 24)
                {
                    _sslStream.BeginRead(state.Buffer, 0, state.Buffer.Length, ReceiveCallback, state);
                }
                else
                {
                    BufferManager.ReturnBuffer(state.Buffer);
                    SendEvent.Set();
                }
            }
            catch (Exception e)
            {
                if (state.Buffer != null)
                {
                    BufferManager.ReturnBuffer(state.Buffer);
                }
                throw;
            }
        }
        public Task <Guid> SendRequestDataAsync(
            Uri requestUri,
            int statusCode,
            string requestBody,
            string responseBody,
            string dateHeaderValue,
            Guid?trackingId = null)
        {
            if (requestUri == null)
            {
                throw new ArgumentNullException(nameof(requestUri));
            }
            if (responseBody == null)
            {
                throw new ArgumentNullException(nameof(responseBody));
            }
            if (requestBody == null)
            {
                throw new ArgumentNullException(nameof(requestBody));
            }

            var actualTrackingId = trackingId ?? Guid.NewGuid();

            // Parse api data
            ApiData apiData = null;

            try {
                apiData = ApiParser.ParseResponse(requestUri, statusCode, requestBody, responseBody, dateHeaderValue);
            }
            catch (Exception ex) {
                this.InternalError?.Invoke(this, new InternalErrorEventArgs(actualTrackingId, "Failed to parse api call data.", ex, apiData));
                return(Task.FromResult(Guid.Empty));
            }

            // Enqueue api data
            try {
                if (apiData != null)
                {
                    try {
                        lock (QueueLock) {
                            if (Queue.Count >= MaxQueueLength)
                            {
                                new InvalidOperationException("Reached to maximum queue size limit.");
                            }

                            var item = new QueueItem {
                                TrackingId = actualTrackingId,
                                ApiData    = apiData
                            };
                            Queue.Enqueue(item);
                        }
                    }
                    catch (Exception ex) {
                        this.FatalError?.Invoke(this, new FatalErrorEventArgs("Failed to enqueue the api data.", ex));
                    }
                }
            }
            catch (Exception ex) {
                this.InternalError?.Invoke(this, new InternalErrorEventArgs(actualTrackingId, "Failed to enqueu API call data.", ex, apiData));
                return(Task.FromResult(Guid.Empty));
            }

            // trigger sending
            try {
                lock (ThreadLock) {
                    if (sendingTaskAwaiter_ == null)
                    {
                        sendingTaskAwaiter_ = SendingThread(ThreadCancellationTokenSource.Token).ConfigureAwait(false);
                    }
                    SendEvent.Set();
                }
            }
            catch (Exception ex) {
                this.InternalError?.Invoke(this, new InternalErrorEventArgs(actualTrackingId, "Failed to trigger sending or creating new thread.", ex, apiData));
            }

            return(Task.FromResult(actualTrackingId));
        }