/// <summary>
        /// Closes the connection to the client. Uses the status information from <see cref="Status"/>, if its CloseStatus
        /// has a value. Otherwise the specified CloseStatus and StatusDescription are used.
        /// </summary>
        /// <param name="closeStatus">Reason for closing the connection (if no Status.CloseStatus is set).</param>
        /// <param name="statusDescription">Description of the reason (if no Status.CloseStatus is set).</param>
        /// <returns></returns>
        public async Task Close(WebSocketCloseStatus closeStatus = WebSocketCloseStatus.Empty, string statusDescription = "")
        {
            if (_isClosed)
            {
                return;
            }

            _isClosed = true;

            // WebSocket must be in state "Open", "CloseReceived" or "CloseSent"
            if (_webSocket.State != WebSocketState.Open && _webSocket.State != WebSocketState.CloseReceived && _webSocket.State != WebSocketState.CloseSent)
            {
                return;
            }

            if (Status.CloseStatus.HasValue)
            {
                await _webSocket.CloseAsync(Status.CloseStatus.Value, Status.CloseStatusDescription, CancellationToken.None);
            }
            else
            {
                await _webSocket.CloseAsync(closeStatus, statusDescription, CancellationToken.None);
            }

            ConnectionClosed?.Invoke(this, EventArgs.Empty);
        }
Exemple #2
0
        public CommunicatingApplicationHook(System.Diagnostics.Process targetProcess)
            : base(targetProcess)
        {
            remoteProcess = new Native.Process.RemoteProcess(targetProcess);
            IPC.NamedPipes.NamedPipeServer server = new IPC.NamedPipes.NamedPipeServer();

            PipeId = Guid.NewGuid().ToString();

            Thread t = new Thread(() =>
            {
                server.ConnectionRecieved += (s, e) =>
                {
                    connection = e.Value;
                    while (e.Value.IsConnected)
                    {
                        var msg = e.Value.Receive();
                        if (e.Value.IsConnected && msg != null)
                        {
                            MessageReceived.RaiseEvent(this, msg);
                        }
                    }
                    ConnectionClosed.RaiseEvent(this);
                };
                server.Start(new IPC.NamedPipes.NamedPipeInitialisation(PipeId));
            });

            t.Start();
        }
        public void GetPhoneNumber_WhenCalledWithVoidMethod_Verify()
        {
            // Arrange, Act
            Instance.GetPhoneNumber();

            // Assert
            this.ShouldSatisfyAllConditions(
                () => Records.Count.ShouldBe(15),
                () => Instance.Id.ShouldHaveSingleItem());
            this.ShouldSatisfyAllConditions(
                () => Records.ShouldContain(Tuple.Create("Area", "0121", DbType.String, (Object)null)),
                () => Records.ShouldContain(Tuple.Create("Area", "0122", DbType.String, (Object)null)),
                () => Records.ShouldContain(Tuple.Create("Area", "0123", DbType.String, (Object)null)),
                () => Records.ShouldContain(Tuple.Create("Area", "0124", DbType.String, (Object)null)),
                () => Records.ShouldContain(Tuple.Create("Major", "3455", DbType.String, (Object)null)),
                () => Records.ShouldContain(Tuple.Create("Major", "3456", DbType.String, (Object)null)),
                () => Records.ShouldContain(Tuple.Create("Major", "3457", DbType.String, (Object)null)),
                () => Records.ShouldContain(Tuple.Create("Major", "3458", DbType.String, (Object)null)),
                () => Records.ShouldContain(Tuple.Create("Major", "3459", DbType.String, (Object)null)),
                () => Records.ShouldContain(Tuple.Create("Major", "34510", DbType.String, (Object)null)),
                () => Records.ShouldContain(Tuple.Create("Major", "34511", DbType.String, (Object)null)),
                () => Records.ShouldContain(Tuple.Create("Major", "345", DbType.String, (Object)null)),
                () => Records.ShouldContain(Tuple.Create("Minor", "6789", DbType.String, (Object)null)),
                () => Records.ShouldContain(Tuple.Create("ToString", "(012)345-6789--Area: 012Major: 345MinorMinor: 6789", DbType.String, (Object)null)),
                () => Records.ShouldContain(Tuple.Create("FizzBuzz", "FizzBuzz", DbType.String, (Object)null)),
                () => ConnectionClosed.ShouldBeTrue(),
                () => ExecuteScalar.ShouldBeTrue(),
                () => ConnectionOpen.ShouldBeTrue(),
                () => Disposed.ShouldBe(1),
                () => Instance.Id.ShouldContain(1));
        }
Exemple #4
0
        public virtual void RemoveConnection(IConnection connection, bool withError)
        {
            ClearListeners(connection);
            connection.Dispose();

            ConnectionClosed?.Invoke(withError);
        }
Exemple #5
0
        // TO DO: Better error reporting on this method.
        public void Shutdown()
        {
            if (Client != null)
            {
                try {
                    lock (ShutdownConnectionLock) {
                        if (NetworkStream != null)
                        {
                            NetworkStream.Close();
                            NetworkStream.Dispose();
                            NetworkStream = null;
                        }

                        Client.Close();
                        Client = null;

                        if (ConnectionClosed != null)
                        {
                            FrostbiteConnection.RaiseEvent(ConnectionClosed.GetInvocationList(), this);
                        }
                    }
                }
                catch (SocketException) {
                    // TO DO: Error reporting, possibly in a log file.
                }
                catch (Exception e) {
                    FrostbiteConnection.LogError("FrostbiteLayerConnection.Shutdown", "catch (Exception e)", e);
                }
            }
        }
Exemple #6
0
 public void ShutdownListener()
 {
     try
     {
         listener.Shutdown(SocketShutdown.Both);
         listener.Close();
         ConnectionClosed?.Invoke(this, new SocketData {
             Data = "conexão fechada!"
         });
         ConnectionClosed   = null;
         ConnectionAccepted = null;
         DataReceived       = null;
     }
     catch (ObjectDisposedException)
     {
     }
     catch (ArgumentNullException ane)
     {
         Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
     }
     catch (SocketException se)
     {
         Console.WriteLine("SocketException : {0}", se.ToString());
     }
     catch (Exception e)
     {
         Console.WriteLine("Unexpected exception : {0}", e.ToString());
     }
 }
Exemple #7
0
        public virtual async ValueTask RemoveConnectionAsync(IConnection connection, bool withError, CancellationToken cancellationToken = default)
        {
            ClearListeners(connection);
            await connection.DisposeAsync();

            ConnectionClosed?.Invoke(withError);
        }
Exemple #8
0
 public void Dispose()
 {
     _intercomServer.ConnectionClosed -= OnConnectionClosed;
     ConnectionClosed?.Invoke(this, EventArgs.Empty);
     _intercomClient?.Dispose();
     _intercomServer?.Dispose();
 }
        private async Task HandleTcpClientAsync(TcpClient tcpClient, int id, CancellationToken cancellationToken)
        {
            try
            {
                var tcpConnection = new TcpConnection(tcpClient);
                ConnectionAccepted?.Invoke(this, new ConnectionAcceptedEventArgs <TcpConnection> {
                    Connection = tcpConnection, AuthenticatedUserName = null
                });

                try
                {
                    await tcpConnection.WhenClosed();
                }
                finally
                {
                    ConnectionClosed?.Invoke(this, new ConnectionEventArgs <TcpConnection> {
                        Connection = tcpConnection
                    });
                }
            }
            finally
            {
                Task dummy;
                activeConnections.TryRemove(id, out dummy);
            }
        }
Exemple #10
0
        private void DataReceive()
        {
            while (Tcp?.Connected ?? false)
            {
                try {
                    byte message = Reader.ReadByte();
                    switch (message)
                    {
                    case COMMAND_BYTE:
                        byte command       = Reader.ReadByte();
                        byte processNumber = Reader.ReadByte();
                        CommandReceived(command, processNumber);
                        break;

                    case TEXT_BYTE:
                        string text = Reader.ReadString();
                        processNumber = Reader.ReadByte();
                        if (!string.IsNullOrEmpty(text))
                        {
                            TextReceived(text, processNumber);
                        }
                        break;
                    }
                }
                catch {
                    ConnectionClosed?.Invoke(this, EventArgs.Empty);
                    return;
                }
            }
            ConnectionClosed?.Invoke(this, EventArgs.Empty);
        }
Exemple #11
0
 private void Run()
 {
     try
     {
         while (true)
         {
             NetworkStream stream    = _tcpClient.GetStream();
             int           messageId = stream.ReadByte();
             Console.WriteLine(messageId);
             if (messageId == -1)
             {
                 ConnectionClosed?.Invoke(this, new ConnectionClosedEventArgs());
                 break;
             }
             MessageReceived?.Invoke(this, new MessageReceivedEventArgs(messageId, stream));
         }
     }
     catch (IOException e)
     {
         if (_manualRefusal)
         {
             Disconnected?.Invoke(this, new DisconnectedEventArgs());
         }
         else
         {
             ConnectionRefused?.Invoke(this, new ConnectionRefusedEventArgs(e));
         }
     }
     catch
     {
         ConnectionClosed?.Invoke(this, new ConnectionClosedEventArgs());
     }
 }
Exemple #12
0
        /// <summary>
        ///     Listens for messages from the server
        /// </summary>
        private void Listen()
        {
            string inputLine = null;

            while ((inputLine = reader.ReadLine()) != null)
            {
                try
                {
                    if (inputLine[0] != '@')
                    {
                        ProcessData(inputLine, new Badge());
                    }
                    else
                    {
                        ParseBagedData(inputLine);
                    }
                }
                catch (Exception ex)
                {
                    ExceptionThrown?.Invoke(this, new ExceptionEventArgs(ex));
                }
            }

            ConnectionClosed?.Invoke(this, new EventArgs());
        }
Exemple #13
0
        public void Close()
        {
            _terminal?.ConsoleOutStream?.Close();
            _reader?.Dispose();

            ConnectionClosed?.Invoke(this, _terminal.ExitCode);
        }
        internal void Stop(ConnectionLossType cause)
        {
            if (stopping)
            {
                return;
            }
            else
            {
                stopping = true;
            }

            ConnectionToken?.Cancel();
            lastConnectionTestStopwatch?.Stop();
            pollingService?.Change(-1, -1);
            connectionStatusService?.Change(-1, -1);
            if (connection.ConnectionState == ConnectionState.Connected)
            {
                Send(Protocol.Connection_Close);
                Send(Protocol.Connection_Close);
            }

            connection.UnInitialize();
            ConnectionClosed?.Invoke(cause);
            connection.ConnectionState = ConnectionState.Offline;
        }
Exemple #15
0
        public void Disconnect()
        {
            if (_state == ConnectionState.Disconnected)
            {
                return;
            }
            _socket.Close();
            _socket = null;
            _state  = ConnectionState.Disconnected;

            try
            {
                //dispatch call into the proper thread
                _context.Post(s =>
                {
                    ConnectionClosed?.Invoke();
                }, null);
                //ConnectionClosed?.Invoke();
            }
            catch (Exception ex)
            {
                //dont trust user code
                Console.WriteLine("Calling client ConnectionClosed event handler threw an exception");
            }
        }
Exemple #16
0
        private void HandleClose(ConnectionInfo info, IActorRef closeCommander, ConnectionClosed closedEvent)
        {
            SetStatus(ConnectionStatus.ShutdownRequested);

            if (closedEvent is Aborted)
            {
                if (traceLogging)
                {
                    Log.Debug("Got Abort command. RESETing connection.");
                }
                DoCloseConnection(info, closeCommander, closedEvent);
            }
            else if (closedEvent is PeerClosed && info.KeepOpenOnPeerClosed)
            {
                // report that peer closed the connection
                info.Handler.Tell(PeerClosed.Instance);
                // used to check if peer already closed its side later
                peerClosed = true;
                Context.Become(PeerSentEOF(info));
            }
            else if (IsWritePending)   // finish writing first
            {
                UnsignDeathPact();
                if (traceLogging)
                {
                    Log.Debug("Got Close command but write is still pending.");
                }
                Context.Become(ClosingWithPendingWrite(info, closeCommander, closedEvent));
            }
            else if (closedEvent is ConfirmedClosed) // shutdown output and wait for confirmation
            {
                if (traceLogging)
                {
                    Log.Debug("Got ConfirmedClose command, sending FIN.");
                }

                // If peer closed first, the socket is now fully closed.
                // Also, if shutdownOutput threw an exception we expect this to be an indication
                // that the peer closed first or concurrently with this code running.
                if (peerClosed || !SafeShutdownOutput())
                {
                    DoCloseConnection(info, closeCommander, closedEvent);
                }
                else
                {
                    Context.Become(Closing(info, closeCommander));
                }
            }
            // close gracefully now
            else
            {
                if (traceLogging)
                {
                    Log.Debug("Got Close command, closing connection.");
                }
                Socket.Shutdown(SocketShutdown.Both);
                DoCloseConnection(info, closeCommander, closedEvent);
            }
        }
        private void Connection_ServiceClosed(AppServiceConnection sender, AppServiceClosedEventArgs args)
        {
            appServiceConnection.RequestReceived -= Connection_RequestReceived;
            appServiceConnection.ServiceClosed   -= Connection_ServiceClosed;
            appServiceConnection = null;

            ConnectionClosed?.Invoke(this);
        }
Exemple #18
0
        protected virtual void OnConnectionClosed()
        {
            // DEBUG: Log connection closed.
            Log.Debug($"Connection to ('{_address}:{_port}') was closed.");

            ConnectionState = ClientConnectionState.Disconnected;
            ConnectionClosed?.Invoke(this, new EventArgs());
        }
Exemple #19
0
 public void Close()
 {
     _port.Close();
     if (!_port.IsOpen)
     {
         ConnectionClosed?.Invoke(this);
     }
 }
Exemple #20
0
 public MessageHandler(IChannel channel, MessageReceived <T> onMessage, ConnectionClosed <T> onConnectionClosed,
                       ConnectionOpened <T> onConnectionOpened)
 {
     this.Channel            = channel;
     this.OnMessage          = onMessage;
     this.OnConnectionClosed = onConnectionClosed;
     this.OnConnectionOpened = onConnectionOpened;
 }
        protected virtual void OnConnectionClosed()
        {
            State = ConnectionState.Closed;

            if (ConnectionClosed != null)
            {
                ConnectionClosed.call(this, EventArgs.Empty);
            }
        }
Exemple #22
0
        private void OnConnectionClosed(object sender, ConnectionClosedEventArgs args)
        {
            if (args.ClosedByPeer)
            {
                Log.ConnectionClosed(_logger, args.Error);
                _writer.TryWrite(ConnectCommand.Instance);
            }

            ConnectionClosed?.Invoke(sender, args);
        }
 private void Close()
 {
     CustomTools.Console.DebugLog("Client::Close() Close client");
     CloseWebSocket();
     if (SendFromThread)
     {
         sendingQueue.Clear();
     }
     ConnectionClosed.SafeInvoke(this);
 }
Exemple #24
0
        private void Handler_Closed(FtpSocketHandler handler)
        {
            m_apConnections.Remove(handler);

            numberOfConnections = m_apConnections.Count;

            Trace.WriteLine($"Remover a handler, current connection number is {numberOfConnections}", "Information");

            ConnectionClosed?.Invoke(handler.Id);
        }
        public void Close()
        {
            int exitCode = -1;

            if (_shellProcess != null && _shellProcess.HasExited)
            {
                exitCode = _shellProcess.ExitCode;
            }
            ConnectionClosed?.Invoke(this, exitCode);
        }
Exemple #26
0
        public void NotifyConnectionClosed(string connectionId)
        {
            SignalRConnection connection;

            if (connections.TryRemove(connectionId, out connection))
            {
                connection.NotifyClosed();
                ConnectionClosed?.Invoke(this, new ConnectionEventArgs <SignalRConnection>()
                {
                    Connection = connection
                });
            }
        }
Exemple #27
0
 void Close()
 {
     Unity.Console.DebugLog("Client::Close() Close client");
     CloseWebSocket();
     if (SendFromThread)
     {
         sendingQueue.Clear();
     }
     if (!ConnectionClosed.IsNull())
     {
         ConnectionClosed(this);
     }
 }
        public void GetPhoneNumber_WhenCalled_Verify(bool voidMethod)
        {
            // Arrange, Act
            if (voidMethod)
            {
                Instance.GetPhoneNumber();
            }
            else
            {
                Instance.SavePhoneNumber();
            }

            // Assert
            this.ShouldSatisfyAllConditions(
                () => Instance.Id.ShouldHaveSingleItem(),
                () => Records.Count.ShouldBeGreaterThanOrEqualTo(2));

            if (CheckParameter("True"))
            {
                Records.Count.ShouldBe(15);
                this.ShouldSatisfyAllConditions(
                    () => Records.ShouldContain(Tuple.Create("Area", "0121", DbType.String, (Object)null)),
                    () => Records.ShouldContain(Tuple.Create("Area", "0122", DbType.String, (Object)null)),
                    () => Records.ShouldContain(Tuple.Create("Area", "0123", DbType.String, (Object)null)),
                    () => Records.ShouldContain(Tuple.Create("Area", "0124", DbType.String, (Object)null)),
                    () => Records.ShouldContain(Tuple.Create("Major", "3455", DbType.String, (Object)null)),
                    () => Records.ShouldContain(Tuple.Create("Major", "3456", DbType.String, (Object)null)),
                    () => Records.ShouldContain(Tuple.Create("Major", "3457", DbType.String, (Object)null)),
                    () => Records.ShouldContain(Tuple.Create("Major", "3458", DbType.String, (Object)null)),
                    () => Records.ShouldContain(Tuple.Create("Major", "3459", DbType.String, (Object)null)),
                    () => Records.ShouldContain(Tuple.Create("Major", "34510", DbType.String, (Object)null)),
                    () => Records.ShouldContain(Tuple.Create("Major", "34511", DbType.String, (Object)null)),
                    () => Records.ShouldContain(Tuple.Create("Major", "345", DbType.String, (Object)null)),
                    () => Records.ShouldContain(Tuple.Create("Minor", "6789", DbType.String, (Object)null)),
                    () => Records.ShouldContain(Tuple.Create("ToString", "(012)345-6789--Area: 012Major: 345MinorMinor: 6789", DbType.String, (Object)null)),
                    () => Records.ShouldContain(Tuple.Create("FizzBuzz", "FizzBuzz", DbType.String, (Object)null)),
                    () => ConnectionClosed.ShouldBeTrue(),
                    () => ExecuteScalar.ShouldBeTrue(),
                    () => ConnectionOpen.ShouldBeTrue(),
                    () => Disposed.ShouldBe(1),
                    () => Instance.Id.ShouldContain(1));
            }

            if (CheckParameter("False"))
            {
                this.ShouldSatisfyAllConditions(
                    () => ShouldContain(Records, "Parameter1", "", DbType.String, (string)null),
                    () => ShouldContain(Records, "FizzBuzz", "FizzBuzz", DbType.String, (string)null),
                    () => Instance.Id.ShouldContain(111));
            }
        }
Exemple #29
0
        // TODO: Detect when WCF sends a closed signal
        public IServerService Connect(IClientCallback clientCallback)
        {
            InstanceContext context = new InstanceContext(clientCallback);

            DuplexChannelFactory <IServerService> channelFactory = new DuplexChannelFactory <IServerService>(context, new NetNamedPipeBinding(), new EndpointAddress(ConnectionConstants.EndpointFullAddress));

            channelFactory.Closed  += (sender, args) => ConnectionClosed?.Invoke(this, EventArgs.Empty);
            channelFactory.Faulted += (sender, args) => ConnectionFaulted?.Invoke(this, EventArgs.Empty);

            IServerService service = channelFactory.CreateChannel();

            service.Connect();
            return(service);
        }
Exemple #30
0
        private async void runReceiveLoop(CancellationToken token)
        {
            try
            {
                byte[] buffer = new byte[32 * 1 << 20];
                while (!_disposed && _client != null && _client.Connected)
                {
                    token.ThrowIfCancellationRequested();

                    int totalRxed = 0;
                    int justRxed  = 0;
                    do
                    {
                        if (buffer.Length - totalRxed <= 0)
                        {
                            throw new InvalidOperationException("Message too large to receive!");
                        }

                        justRxed = await _client.GetStream().ReadAsync(buffer, totalRxed, buffer.Length - totalRxed, token);

                        totalRxed += justRxed;
                    } while (justRxed == _client.ReceiveBufferSize);

                    if (totalRxed > 0)
                    {
                        try
                        {
                            RpcResponse response = MessagePackSerializer.Deserialize <RpcResponse>(buffer);
                            response.ResultAsJson = JsonConvert.SerializeObject(response.Result);
                            taskForRequest(response.MsgId).SetResult(response);
                        }
                        catch (Exception ex) when(!(ex is OperationCanceledException) || !(ex is ObjectDisposedException) || !(ex is IOException))  // MessagePack failure
                        {
                            _client.Dispose();
                            _client = null;
                            failAllTasks(ex.Message);
                        }
                    }
                }
            }
            catch (Exception ex) when(ex is OperationCanceledException || ex is ObjectDisposedException || ex is IOException)
            {
            }
            finally
            {
                failAllTasks("Client closed");
                ConnectionClosed?.Invoke(this, EventArgs.Empty);
            }
        }
 private void HandleConnectionClosed(ConnectionClosed message)
 {
     Console.WriteLine("Connection closed");
     Context.Stop(Self);
     Context.Parent.Tell(message);
 }