Пример #1
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());
     }
 }
Пример #2
0
        public virtual async ValueTask RemoveConnectionAsync(IConnection connection, bool withError, CancellationToken cancellationToken = default)
        {
            ClearListeners(connection);
            await connection.DisposeAsync();

            ConnectionClosed?.Invoke(withError);
        }
Пример #3
0
        public void Close()
        {
            _terminal?.ConsoleOutStream?.Close();
            _reader?.Dispose();

            ConnectionClosed?.Invoke(this, _terminal.ExitCode);
        }
        /// <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);
        }
Пример #5
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());
        }
Пример #6
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");
            }
        }
Пример #7
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);
        }
Пример #8
0
        public virtual void RemoveConnection(IConnection connection, bool withError)
        {
            ClearListeners(connection);
            connection.Dispose();

            ConnectionClosed?.Invoke(withError);
        }
Пример #9
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());
     }
 }
Пример #10
0
        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);
            }
        }
Пример #11
0
 public void Dispose()
 {
     _intercomServer.ConnectionClosed -= OnConnectionClosed;
     ConnectionClosed?.Invoke(this, EventArgs.Empty);
     _intercomClient?.Dispose();
     _intercomServer?.Dispose();
 }
        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;
        }
Пример #13
0
 public void Close()
 {
     _port.Close();
     if (!_port.IsOpen)
     {
         ConnectionClosed?.Invoke(this);
     }
 }
Пример #14
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());
        }
        private void Connection_ServiceClosed(AppServiceConnection sender, AppServiceClosedEventArgs args)
        {
            appServiceConnection.RequestReceived -= Connection_RequestReceived;
            appServiceConnection.ServiceClosed   -= Connection_ServiceClosed;
            appServiceConnection = null;

            ConnectionClosed?.Invoke(this);
        }
Пример #16
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);
        }
Пример #17
0
        public void Close()
        {
            int exitCode = -1;

            if (_shellProcess != null && _shellProcess.HasExited)
            {
                exitCode = _shellProcess.ExitCode;
            }
            ConnectionClosed?.Invoke(this, exitCode);
        }
Пример #18
0
        private void OnConnectionClosed(object sender, ConnectionClosedEventArgs args)
        {
            if (args.ClosedByPeer)
            {
                Log.ConnectionClosed(_logger, args.Error);
                _writer.TryWrite(ConnectCommand.Instance);
            }

            ConnectionClosed?.Invoke(sender, args);
        }
Пример #19
0
        public void NotifyConnectionClosed(string connectionId)
        {
            SignalRConnection connection;

            if (connections.TryRemove(connectionId, out connection))
            {
                connection.NotifyClosed();
                ConnectionClosed?.Invoke(this, new ConnectionEventArgs <SignalRConnection>()
                {
                    Connection = connection
                });
            }
        }
Пример #20
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);
        }
Пример #21
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);
            }
        }
Пример #22
0
 /// <summary>
 /// Fired by maintenance timer.
 /// </summary>
 private void Timer_Callback()
 {
     try
     {
         if (_stop)
         {
             _client.Close();
             ConnectionClosed?.Invoke(this);
         }
     }
     catch (Exception ex)
     {
         ErrorHandler.LogError(ex);
     }
 }
Пример #23
0
        protected void OnWebSocketClosed()
        {
            DebugLogger.Log("[SnipeClient] OnWebSocketClosed");

            Disconnect();

            try
            {
                ConnectionClosed?.Invoke();
            }
            catch (Exception e)
            {
                DebugLogger.Log($"[SnipeClient] OnWebSocketClosed - ConnectionClosed invokation error: {e.Message}\n{e.StackTrace}");
            }
        }
Пример #24
0
        private void handler_Closed(FtpSocketHandler handler)
        {
            lock (m_apConnections)
            {
                m_apConnections.Remove(handler);

                LogWrite(
                    $"Client closed: {handler.RemoteEndPoint} current count={m_apConnections.Count}");
                Trace.WriteLine(
                    $"Handler closed {handler.RemoteEndPoint}. Current Count {m_apConnections.Count}",
                    "Information");

                ConnectionClosed?.Invoke(handler.Id);
            }
        }
Пример #25
0
        protected async Task ProcessMessage()
        {
            var messages = await GetMessages().ConfigureAwait(false);

            if (messages is null)
            {
                return;
            }

            foreach (var message in messages)
            {
                switch (message.Code)
                {
                case WebSocketFrame.OpCode.ContinuationFrame:
                    ContinuationFrameReceived?.Invoke(this, Encoding.UTF8.GetString(message.Data));
                    break;

                case WebSocketFrame.OpCode.TextFrame:
                    if (message.Data.Length > 0)
                    {
                        MessageReceived?.Invoke(this, Encoding.UTF8.GetString(message.Data));
                    }
                    break;

                case WebSocketFrame.OpCode.BinaryFrame:
                    BinaryMessageReceived?.Invoke(this, message.Data);
                    break;

                case WebSocketFrame.OpCode.ConnectionClose:
                    TcpClient.Close();
                    var code = BitConverter.ToUInt16(message.Data.Take(2).Reverse().ToArray(), 0);
                    ConnectionClosed?.Invoke(this, (WebSocketFrame.CloseStatusCode)code);
                    break;

                case WebSocketFrame.OpCode.Ping:
                    Ping?.Invoke(this, null);
                    break;

                case WebSocketFrame.OpCode.Pong:
                    Pong?.Invoke(this, null);
                    break;

                default:
                    Console.WriteLine("Not supported command.");
                    break;
                }
            }
        }
Пример #26
0
        public static void Close()
        {
            if (!IsOpen)
            {
                return;
            }

            IsOpen = false;

            s_SerialPort.Close();
            s_SerialPort.Dispose();
            s_SerialPort = null;
            s_GotResponse.Reset();

            ConnectionClosed?.Invoke(null, EventArgs.Empty);
        }
Пример #27
0
        public static void Close()
        {
            Logging.WriteBannerToLog("Close");

            if (!IsOpen)
            {
                return;
            }

            CloseInternal();

            Logging.WriteLineToLog("Serial port is closed.");
            IsOpen = false;

            ConnectionClosed?.Invoke(null, EventArgs.Empty);
        }
Пример #28
0
        private void Client_ConnectionFailed(Exception ex)
        {
            if (ex != null)
            {
#if DEBUG
                LogMessage("Could not connect to the server: " + ex);
#else
                LogMessage("Could not connect to the server: " + ex.Message);
#endif
            }
            else
            {
                LogMessage("Could not connect to the server.");
            }
            ConnectionClosed?.Invoke();
            SetClient(null);
        }
        public SerialPortRUSConnectionInterface(IInterface port)
        {
            _port = port;

            _port.ConnectionEstablished += _base_ConnectionEstablished;
            _port.ConnectionClosed      += _base_ConnectionClosed;

            void _base_ConnectionClosed(object sender, EventArgs e)
            {
                ConnectionClosed?.Invoke(sender, e);
            }

            void _base_ConnectionEstablished(object sender, EventArgs e)
            {
                ConnectionEstablished?.Invoke(sender, e);
            }
        }
Пример #30
0
        private void Client_ConnectionClosed(Exception ex)
        {
            if (ex != null)
            {
#if DEBUG
                LogMessage("Disconnected from the server: " + ex, Brushes.OrangeRed);
#else
                LogMessage("Disconnected from the server: " + ex.Message, Brushes.OrangeRed);
#endif
            }
            else
            {
                LogMessage("Disconnected from the server.", Brushes.OrangeRed);
            }
            ConnectionClosed?.Invoke();
            SetClient(null);
        }