Ejemplo n.º 1
0
        private async Task WatcherLoop(CancellationToken cancellationToken)
        {
            try
            {
                Watching = true;

                await foreach (var(t, evt) in CreateWatchEventEnumerator(_streamReaderCreator, OnError,
                                                                         cancellationToken)
                               .ConfigureAwait(false)
                               )
                {
                    OnEvent?.Invoke(t, evt);
                }
            }
            catch (OperationCanceledException)
            {
                // ignore
            }
            catch (Exception e)
            {
                // error when transport error, IOException ect
                OnError?.Invoke(e);
            }
            finally
            {
                Watching = false;
                OnClosed?.Invoke();
            }
        }
Ejemplo n.º 2
0
 public MessageCenter(TransportManager transportManager)
 {
     _transportManager              = transportManager;
     _transportManager.OnConnected += (p, e, _) => OnConnected?.Invoke(e.ToUri(p));
     _transportManager.OnReceived  += OnReceive;
     _transportManager.OnClosed    += (p, e, _) => OnClosed?.Invoke(e.ToUri(p));
 }
 public async Task ClosedCall()
 {
     if (OnClosed != null)
     {
         await OnClosed?.Invoke();
     }
 }
Ejemplo n.º 4
0
 private void Am_OnAnimationFinished(object sender)
 {
     Height           = 0;
     BindedTimedEvent = null;
     Invalidate();
     OnClosed?.Invoke(this);
 }
        public void Close <T>() where T : Popup
        {
            if (_activePopupStack.IsEmpty() || _activePopupStack.Peek().GetType() != typeof(T))
            {
                return;
            }

            Popup popup = _activePopupStack.Get <T>();

            popup.AnimateOut(() =>
            {
                _activePopupStack.Pop();

                PreviousPopup = CurrentPopup;
                CurrentPopup  = null;

                OnClosed?.Invoke(popup.GetType());
                popup.Clear();

                if (_activePopupStack.Count > 0)
                {
                    OpenFromStack();
                }
            });
        }
Ejemplo n.º 6
0
        private void ProcessReceive(object sender, SocketAsyncEventArgs eventArgs)
        {
            if (eventArgs.SocketError != SocketError.Success)
            {
                Console.Error.WriteLine($"Error {eventArgs.SocketError.ToString()}");
            }

            (var transport, var transportMessage) = ((TcpClientTransport, TransportMessage))eventArgs.UserToken;

            if (eventArgs.BytesTransferred == 0)
            {
                OnClosed?.Invoke(ProtocolType.Tcp, _remoteEndPoint, eventArgs);
                eventArgs.Dispose();
                return;
            }

            transportMessage.UpdateBytesReceived();

            // Check if we're done
            if (transportMessage.IsReady)
            {
                OnReceived?.Invoke(ProtocolType.Tcp, _remoteEndPoint, transportMessage);
                transportMessage.Reset();
            }

            StartReceivingAsync(eventArgs);
        }
Ejemplo n.º 7
0
 public Task CloseAsync()
 {
     if (_socket == null)
     {
         throw new InvalidOperationException("Close failed, must connect first.");
     }
     else
     {
         _tokenSource.Cancel();
         _tokenSource.Dispose();
         _socket.Abort();
         _receiverLoop.Abort();
         _senderLoop.Abort();
         _socket.Dispose();
         WakeSenderLoop();
         State   = SocketState.Closed;
         _socket = null;
         if (serverCloseReason != ServerCloseReason.SocketClosedByClient)
         {
             OnClosed?.Invoke(serverCloseReason);
         }
         else
         {
             OnClosed?.Invoke(ServerCloseReason.SocketClosedByClient);
         }
         // SocketClosedByClient
         return(Task.CompletedTask);
     }
 }
        public override Dialog OnCreateDialog(Bundle savedInstanceState)
        {
            var builder  = new AlertDialog.Builder(Activity);
            var inflater = Activity.LayoutInflater;

            var selectedDate = GetSelectedDate();

            var dialog = inflater.Inflate(Resource.Layout.date_picker_dialog, null);

            _monthPicker = (NumberPicker)dialog.FindViewById(Resource.Id.picker_month);
            _yearPicker  = (NumberPicker)dialog.FindViewById(Resource.Id.picker_year);

            InitializeMonthPicker(selectedDate.Month);
            InitializeYearPicker(selectedDate.Year);
            SetMaxMinDate(MaxDate, MinDate);

            builder.SetView(dialog)
            .SetPositiveButton("Ok", (sender, e) =>
            {
                selectedDate = new DateTime(_yearPicker.Value, _monthPicker.Value, DefaultDay);
                OnDateTimeChanged?.Invoke(dialog, selectedDate);
            })
            .SetNegativeButton("Cancel", (sender, e) =>
            {
                Dialog.Cancel();
                OnClosed?.Invoke(dialog, selectedDate);
            })
            .SetNeutralButton("Limpar", (sender, e) =>
            {
                Dialog.Cancel();
                OnClosed?.Invoke(dialog, selectedDate);
            });
            return(builder.Create());
        }
Ejemplo n.º 9
0
        public void Close()
        {
            if (TradeType == TradeType.Buy)
            {
                InputEvent.Instance.Event_SwitchShop.RemoveListener(SwitchMenuToSell);
            }
            else
            {
                InputEvent.Instance.Event_SwitchShop.RemoveListener(SwitchMenuToBuy);
            }

            Left.Deactivate();
            Right.Deactivate();
            Products = null;

            UI_NavigatorManager.Instance.Remove(ref uinav_escapeToCloseShop);
            UI_NavigatorManager.Instance.Remove(ref uinav_tabSellOrBuy);
            InputEvent.Instance.Event_CloseShop.RemoveAllListener();

            UI_Chat_Main.Instance.Dialogue.UpdateDialogue(dialogueAfterShopClosed.ReturnToObject.Dialogue
                                                          , dialogueAfterShopClosed.ReturnToIndex);

            dialogueAfterShopClosed = null;

            OnClosed.Invoke();
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Closes the session's RTP and control ports.
        /// </summary>
        public void Close(string reason)
        {
            if (!m_isClosed)
            {
                try
                {
                    string closeReason = reason ?? "normal";

                    if (m_controlReceiver == null)
                    {
                        logger.LogDebug($"RTPChannel closing, RTP receiver on port {RTPPort}. Reason: {closeReason}.");
                    }
                    else
                    {
                        logger.LogDebug($"RTPChannel closing, RTP receiver on port {RTPPort}, Control receiver on port {ControlPort}. Reason: {closeReason}.");
                    }

                    m_isClosed = true;
                    m_rtpReceiver?.Close(null);
                    m_controlReceiver?.Close(null);

                    OnClosed?.Invoke(closeReason);
                }
                catch (Exception excp)
                {
                    logger.LogError("Exception RTPChannel.Close. " + excp);
                }
            }
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Called when the window closes, used to shutdown client systems.
 /// </summary>
 private void Window_Closed(object sender, EventArgs e)
 {
     if (VR != null)
     {
         VR.Stop();
         VR = null;
     }
     Sounds.Shutdown();
     if (RawGamePad != null)
     {
         RawGamePad.Dispose();
         RawGamePad = null;
     }
     if (LocalServer != null)
     {
         // TODO: ManualReset object?
         Object tlock = new Object();
         bool   done  = false;
         LocalServer.ShutDown(() => { lock (tlock) { done = true; } });
         bool b = false;
         while (!b)
         {
             Thread.Sleep(250);
             lock (tlock)
             {
                 b = done;
             }
         }
     }
     // TODO: Cleanup!
     OnClosed?.Invoke();
     Environment.Exit(0);
 }
Ejemplo n.º 12
0
        private void ProcessReceive(object sender, SocketAsyncEventArgs eventArgs)
        {
            if (eventArgs.SocketError != SocketError.Success)
            {
                Console.Error.WriteLine($"Error {eventArgs.SocketError.ToString()}");
            }

            OnConnected?.Invoke(ProtocolType.Udp, eventArgs.RemoteEndPoint, eventArgs);

            if (eventArgs.BytesTransferred == 0)
            {
                OnClosed?.Invoke(ProtocolType.Udp, eventArgs.RemoteEndPoint, eventArgs);
                eventArgs.Dispose();
                return;
            }

            (var transport, var transportMessage) = ((UdpHostTransport, TransportMessage))eventArgs.UserToken;

            transportMessage.UpdateBytesReceived();

            // For now, UDP messages cannot extend across a single message
            OnReceived?.Invoke(ProtocolType.Udp, eventArgs.RemoteEndPoint, transportMessage);
            transportMessage.Reset(UdpPacketSize);

            _autoResetEvent.Set();
        }
Ejemplo n.º 13
0
        public async Task StartAsync()
        {
            await HandleCommunicationAsync();

            OnConnectionStateChanged?.Invoke(this, new ConnectionStateChangedEventArgs(ConnectionState.Closed));
            OnClosed?.Invoke(this, null);
        }
Ejemplo n.º 14
0
        public async Task ReceiveAsync()
        {
            try {
                while (Socket.State == WebSocketState.Open)
                {
                    var buffer = new byte[512];
                    var result = await Socket.ReceiveAsync(buffer, CancellationToken.None);

                    switch (result.MessageType)
                    {
                    case WebSocketMessageType.Text:
                        if (!result.EndOfMessage)
                        {
                            continue;
                        }

                        var lastIndex = Array.FindLastIndex(buffer, b => b != 0);
                        Array.Resize(ref buffer, lastIndex + 1);
                        OnMessage?.Invoke(this, buffer);
                        continue;

                    case WebSocketMessageType.Close:
                        OnClosed?.Invoke(this);
                        continue;
                    }
                }
            }
            catch {
                OnClosed?.Invoke(this);
            }
        }
Ejemplo n.º 15
0
 private void SetEventHandlers(Options opts)
 {
     opts.AsyncErrorEventHandler       += (sender, args) => OnAsyncError?.Invoke(this, ErrorEventArguments.FromNatsEntity(args));
     opts.ServerDiscoveredEventHandler += (sender, args) => OnServerDiscovered?.Invoke(this, ConnectionEventArguments.FromNatsEntity(args));
     opts.ClosedEventHandler           += (sender, args) => OnClosed?.Invoke(this, ConnectionEventArguments.FromNatsEntity(args));
     opts.DisconnectedEventHandler     += (sender, args) => OnDisconnected?.Invoke(this, ConnectionEventArguments.FromNatsEntity(args));
 }
Ejemplo n.º 16
0
 //---------------------------------------------------------------------
 void _raiseClosed()
 {
     if (OnClosed != null)
     {
         OnClosed.Invoke(null, EventArgs.Empty);
     }
 }
Ejemplo n.º 17
0
        private async Task <string> ReceiveAsync(ClientWebSocket webSocket)
        {
            // TODO: Probably should optimize this (better resource allocation/management)

            byte[] temporaryBuffer = new byte[8192];
            byte[] buffer          = new byte[8192 * 16];
            int    offset          = 0;
            bool   end             = false;

            while (!end)
            {
                WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment <byte>(temporaryBuffer), CancellationToken.None);

                if (result.MessageType == WebSocketMessageType.Close)
                {
                    OnClosed?.Invoke(result.CloseStatus, result.CloseStatusDescription).GetAwaiter();
                    Connected = false;
                    Console.WriteLine(new LogMessage(LogSeverity.Info, "Lavalink", "Disconnected from Lavalink node"));
                }
                else
                {
                    temporaryBuffer.CopyTo(buffer, offset);
                    offset         += result.Count;
                    temporaryBuffer = new byte[8192];

                    if (result.EndOfMessage)
                    {
                        end = true;
                    }
                }
            }

            return(Encoding.UTF8.GetString(buffer));
        }
        private async Task StartSend()
        {
            while (await reader.WaitToReadAsync())
            {
                if (reader.TryRead(out ArraySegment <byte> message))
                {
                    if (clientWebSocket.State != WebSocketState.Open)
                    {
                        throw new WebSocketException(WebSocketError.InvalidState, "Error Sending Message. WebSocket State is: " + clientWebSocket.State);
                    }

                    int messageCount = (int)Math.Ceiling((double)message.Count / SendChunkSize);

                    for (int i = 0; i < messageCount; i++)
                    {
                        int  offset       = SendChunkSize * i;
                        bool endOfMessage = (i == messageCount - 1);
                        int  count        = endOfMessage ? message.Count - offset : SendChunkSize;
                        await clientWebSocket.SendAsync(new ArraySegment <byte>(message.Array, offset, count), WebSocketMessageType.Binary, endOfMessage, cancellationToken).ConfigureAwait(false);
                    }
                }
            }
            // close the socket (listener will therminate after that)
            clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).Wait();
            IsConnected.Reset();
            OnClosed?.Invoke(null, EventArgs.Empty);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Closes and dispose associated underlying database transaction/connection asynchronously.
        /// </summary>
        /// <param name="cancellationToken">Asynchronous operation cancellation token.</param>
        /// <returns>Asynchronous operation completion task.</returns>
        public virtual async Task CloseAsync(CancellationToken cancellationToken = default)
        {
            OnClosing?.Invoke(this, EventArgs.Empty);

            DisposeCommand();

            if (TransactionAsync != null && _closeTransaction)
            {
                TransactionAsync.Dispose();
                TransactionAsync = null;
            }

            if (_connection != null)
            {
                if (_disposeConnection)
                {
                    await _connection.DisposeAsync().ConfigureAwait(Common.Configuration.ContinueOnCapturedContext);

                    _connection = null;
                }
                else if (_closeConnection)
                {
                    await _connection.CloseAsync().ConfigureAwait(Common.Configuration.ContinueOnCapturedContext);
                }
            }

            OnClosed?.Invoke(this, EventArgs.Empty);
        }
Ejemplo n.º 20
0
        public void Close()
        {
            lock (_closeConnLock)
            {
                if (_closed)
                {
                    return;
                }

                _closed = true;
            }

            OnClosed?.Invoke(this, new SSRelayEventArgs(_server));

            try
            {
                _connection.Shutdown(SocketShutdown.Both);
                _connection.Close();

                encryptor?.Dispose();
                decryptor?.Dispose();
            }
            catch (Exception e)
            {
                this.Log().Error(e, "");
            }
        }
Ejemplo n.º 21
0
 /// <summary>
 /// 当关闭时
 /// </summary>
 /// <param name="obj">socket对象</param>
 private void OnSocketClosed(object obj)
 {
     receiveState.Reset();
     if (OnClosed != null)
     {
         OnClosed.Invoke(this, lastException);
     }
 }
 public void Open(string url, string protocol = null)
 {
     _clientWebSocketConnection = ClientWebSocketWrapper.Create(url);
     _clientWebSocketConnection.OnConnect(_ => OnOpened?.Invoke());
     _clientWebSocketConnection.OnDisconnect(_ => OnClosed?.Invoke());
     _clientWebSocketConnection.OnMessage((s, _) => OnMessage?.Invoke(s));
     _clientWebSocketConnection.Connect().Wait();
 }
Ejemplo n.º 23
0
 private Task SocketError(SocketErrorEventArgs e)
 {
     Console.WriteLine("Socket Error!");
     Console.WriteLine(e.ToString());
     Close();
     OnClosed?.Invoke();
     return(Task.CompletedTask);
 }
Ejemplo n.º 24
0
 public void Dispose()
 {
     if (IsOpen)
     {
         Rollback();
     }
     _transactionFlavor?.Dispose();
     OnClosed?.Invoke(this, new TransactionEventArgs(_transactionDomain));
 }
Ejemplo n.º 25
0
 public void Open(string url, string protocol = null)
 {
     socket            = protocol == null ? new WebSocket(url) : new WebSocket(url, protocol);
     socket.OnOpen    += delegate { OnOpened?.Invoke(); };
     socket.OnClose   += delegate { OnClosed?.Invoke(); };
     socket.OnError   += (sender, args) => OnError?.Invoke(args.Message);
     socket.OnMessage += (sender, args) => OnMessage?.Invoke(args.Data);
     socket.Connect();
 }
Ejemplo n.º 26
0
        private void StartMonitor()
        {
            _monitorTask = Task.Run(() =>
            {
                _monitorRunning    = true;
                var needsReconnect = false;
                try
                {
                    var lastState = State;
                    while (_ws != null && !_disposedValue)
                    {
                        if (lastState == State)
                        {
                            Thread.Sleep(200);
                            continue;
                        }

                        OnStateChanged?.Invoke(State, lastState);

                        if (State == WebSocketState.Open)
                        {
                            OnOpened?.Invoke();
                        }

                        if ((State == WebSocketState.Closed || State == WebSocketState.Aborted) && !_reconnecting)
                        {
                            if (lastState == WebSocketState.Open && !_disconnectCalled && _reconnectStrategy != null &&
                                !_reconnectStrategy.AreAttemptsComplete())
                            {
                                // go through the reconnect strategy
                                // Exit the loop and start async reconnect
                                needsReconnect = true;
                                break;
                            }
                            OnClosed?.Invoke(_ws.CloseStatus ?? WebSocketCloseStatus.Empty);
                            if (_ws.CloseStatus != null && _ws.CloseStatus != WebSocketCloseStatus.NormalClosure)
                            {
                                OnError?.Invoke(new Exception(_ws.CloseStatus + " " + _ws.CloseStatusDescription));
                            }
                        }

                        lastState = State;
                    }
                }
                catch (Exception ex)
                {
                    OnError?.Invoke(ex);
                }
                if (needsReconnect && !_reconnecting && !_disconnectCalled)
#pragma warning disable 4014
                {
                    DoReconnect();
                }
#pragma warning restore 4014
                _monitorRunning = false;
            });
        }
        public async Task StartRecive()
        {
            var buffer     = new byte[4096 * 2];
            int startIndex = 0;

            if (clientWebSocket.State != WebSocketState.Open)
            {
                return;
            }

            await SendListPendingMessage();

            while (clientWebSocket.State == WebSocketState.Open)
            {
                var rcvBuffer = new ArraySegment <byte>(buffer, startIndex, buffer.Length - startIndex);
                var response  = await clientWebSocket.ReceiveAsync(rcvBuffer, CancellationToken.None);

                if (response.MessageType == WebSocketMessageType.Close)
                {
                    await clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Close response received",
                                                     CancellationToken.None);

                    onClosed?.Invoke(this, null);
                    return;
                }
                if (response.MessageType == WebSocketMessageType.Binary)
                {
                    if (response.EndOfMessage)
                    {
                        var js  = GZipHelper.Decompress(buffer);
                        var sjs = Encoding.ASCII.GetString(js);
                        // Console.WriteLine("收到的报文为:" + sjs);
                        onRecivedMessage?.Invoke(this, null, sjs);

                        startIndex = 0;
                    }
                    else
                    {
                        startIndex += response.Count;
                    }
                }
            }
        }
        public async void Close()
        {
            if (IsAlive())
            {
                await clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);

                IsConnected.Reset();
                OnClosed?.Invoke(null, EventArgs.Empty);
            }
        }
Ejemplo n.º 29
0
 public void Close()
 {
     if (WebSocket != null)
     {
         WebSocket.Dispose();
         WebSocket = null;
         isAlive   = false;
         OnClosed?.Invoke(null, EventArgs.Empty);
     }
 }
Ejemplo n.º 30
0
        /// <summary>
        /// Closes the socket and stops any new receives from being initiated.
        /// </summary>
        public void Close(string reason)
        {
            if (!m_isClosed)
            {
                m_isClosed = true;
                m_udpSocket?.Close();

                OnClosed?.Invoke(reason);
            }
        }