public void Init(DeviceConfig dvConfig, ILogger logger) { this.Logger = logger; this.Config = dvConfig; this.client = new TcpClientAdapter(); GetConfig(dvConfig); }
public ClientMessageReceivedEventArgs(ITcpClientAdapter client, CancellationToken cancellationToken, ClientMessage clientMessage) { Client = client; CancellationToken = cancellationToken; ClientMessage = clientMessage; }
/// <summary> /// Connects to the specified port on the specified host, optionally using the Secure Socket Layer /// (SSL) security protocol. /// </summary> /// <param name="hostname">The DNS name of the server to which you intend to connect.</param> /// <param name="port">The port number of the server to which you intend to connect.</param> /// <param name="ssl">Set to true to use the Secure Socket Layer (SSL) security protocol.</param> /// <param name="validate">Delegate used for verifying the remote Secure Sockets Layer (SSL) /// certificate which is used for authentication. Can be null if not needed.</param> /// <exception cref="ArgumentOutOfRangeException">The port parameter is not between MinPort /// and MaxPort.</exception> /// <exception cref="ArgumentNullException">The hostname parameter is null.</exception> /// <exception cref="IOException">There was a failure writing to or reading from the /// network.</exception> /// <exception cref="SocketException">An error occurred while accessing the socket used for /// establishing the connection to the IMAP server. Use the ErrorCode property to obtain the /// specific error code.</exception> /// <exception cref="System.Security.Authentication.AuthenticationException">An authentication /// error occured while trying to establish a secure connection.</exception> private void Connect(string host, int port, bool isSsl, RemoteCertificateValidationCallback validate) { if (_client == null) { _client = new TcpClientAdapter { ReceiveTimeout = 20000 }; } if (!_client.Connected) { _client.Connect(host, port); } if (_client.Connected) { _clientStream = _client.GetStream(); if (isSsl) { var sslStream = new SslStream(_clientStream, false, validate ?? ((sender, cert, chain, err) => true)); sslStream.AuthenticateAsClient(host); _clientStream = sslStream; } _response = GetResponse(false); ValidateResponse(_response); } }
public async Task SendMessage(ITcpClientAdapter client, CancellationToken token, string message) { var bytes = Encoding.UTF8.GetBytes(message); _logger.LogFormat("SERVER: {0}", message); await client.GetStream().WriteAsync(bytes, 0, bytes.Length, token).ConfigureAwait(false); }
public void DisconnectClient(ITcpClientAdapter tcpClient) { var clientIdentifier = tcpClient.ClientIdentifier; tcpClient.Close(); if (ClientDisconnected != null) ClientDisconnected(this, new NetworkClientDisconnectedEventArgs(clientIdentifier)); }
public Client(ITcpClientAdapter tcpClient, CancellationToken cancellationToken, IMessager messager, IMimeParser mimeParser) { TcpClient = tcpClient; CancellationToken = cancellationToken; _clientState = new ConnectedState(this, messager, mimeParser); // Change to the 'awaiting EHLO' state _clientState = new AwaitingEhloCommandState(this, messager, mimeParser); }
public void DisconnectClient(ITcpClientAdapter tcpClient) { var clientIdentifier = tcpClient.ClientIdentifier; tcpClient.Close(); if (ClientDisconnected != null) { ClientDisconnected(this, new NetworkClientDisconnectedEventArgs(clientIdentifier)); } }
public void Dispose() { if (_client != null) { _client.Close(); _client = null; } if (_stream != null) { _stream.Close(); _stream = null; } }
public async Task HandleClientAsync(ITcpClientAdapter client, int connections, CancellationToken token) { using (client) { if (ClientConnected != null) { ClientConnected(this, new NetworkClientConnectedEventArgs(client, token)); } var buf = new byte[4096]; using (var stream = client.GetStream()) { while (!token.IsCancellationRequested) { Array.Clear(buf, 0, buf.Length); var timeoutTask = Task.Delay(TimeSpan.FromSeconds(15)); var amountReadTask = stream.ReadAsync(buf, 0, buf.Length, token); var completedTask = await Task.WhenAny(timeoutTask, amountReadTask).ConfigureAwait(false); // Client timed out if (completedTask == timeoutTask) { if (ClientDisconnected != null) { ClientDisconnected(this, new NetworkClientDisconnectedEventArgs(client.ClientIdentifier)); } break; } var amountRead = amountReadTask.Result; if (amountRead == 0) { break; // End of stream } var resultBytes = new byte[amountRead]; Array.Copy(buf, resultBytes, amountRead); if (ClientMessageReceived != null) { ClientMessageReceived(this, new NetworkClientMessageReceivedEventArgs(client, token, resultBytes)); } } } } }
protected void CleanSocket() { Trace(new TraceEventArg(() => "EmailClient::CleanSocket > Entry")); if (_client != null) { _client.Close(); _client = null; } if (_clientStream != null) { _clientStream.Close(); _clientStream = null; } Trace(new TraceEventArg(() => "EmailClient::CleanSocket > Exit")); }
public async Task HandleClientAsync(ITcpClientAdapter client, int connections, CancellationToken token) { using (client) { if (ClientConnected != null) ClientConnected(this, new NetworkClientConnectedEventArgs(client, token)); var buf = new byte[4096]; using (var stream = client.GetStream()) { while (!token.IsCancellationRequested) { Array.Clear(buf, 0, buf.Length); var timeoutTask = Task.Delay(TimeSpan.FromSeconds(15)); var amountReadTask = stream.ReadAsync(buf, 0, buf.Length, token); var completedTask = await Task.WhenAny(timeoutTask, amountReadTask).ConfigureAwait(false); // Client timed out if (completedTask == timeoutTask) { if (ClientDisconnected != null) ClientDisconnected(this, new NetworkClientDisconnectedEventArgs(client.ClientIdentifier)); break; } var amountRead = amountReadTask.Result; if (amountRead == 0) break; // End of stream var resultBytes = new byte[amountRead]; Array.Copy(buf, resultBytes, amountRead); if (ClientMessageReceived != null) ClientMessageReceived(this, new NetworkClientMessageReceivedEventArgs(client, token, resultBytes)); } } } }
public ClientConnectedEventArgs(ITcpClientAdapter client, CancellationToken cancellationToken) { Client = client; CancellationToken = cancellationToken; }
/// <summary> /// Reconnect, if there is a timeout exception and isAutoReconnect is true /// </summary> //private bool ExecuteReconnect(IOException ex, string command) //{ // Trace(new TraceEventArg(() => "EmailClient::ExecuteReconnect > Entry")); // if (ex.InnerException != null && ex.InnerException is SocketException) // { // SocketException innerEx = (SocketException)ex.InnerException; // if (innerEx.ErrorCode == 10053) // { // //probably timeout: An established connection was aborted by the software in your host machine. // if (IsAutoReconnect) // { // //try to reconnect and send one more time // _isTimeoutReconnect = true; // try // { // // try to auto reconnect // initializeConnection(); // SendCommand(command); // Trace(new TraceEventArg(() => "EmailClient::ExecuteReconnect > Exit with True")); // return true; // } // finally // { // _isTimeoutReconnect = false; // } // } // } // } // Trace(new TraceEventArg(() => "EmailClient::ExecuteReconnect > Exit with False")); // return false; //} internal void SetTcpClient(ITcpClientAdapter client) { _client = client; }
public NetworkClientMessageReceivedEventArgs(ITcpClientAdapter client, CancellationToken cancellationToken, byte[] message) { Client = client; CancellationToken = cancellationToken; Message = message; }
public void Init(DeviceConfig dvConfig, ITcpClientAdapter client, ILogger logger) { this.client = client; Init(dvConfig, logger); }
public NetworkClientConnectedEventArgs(ITcpClientAdapter client, CancellationToken cancellationToken) { Client = client; CancellationToken = cancellationToken; }
private void connect(string host, int port, bool isSsl, RemoteCertificateValidationCallback validate) { if (_client == null) { _client = new TcpClientAdapter { ReceiveTimeout = 20000 }; } if (!_client.Connected) { try { _client.Connect(host, port); } catch (SocketException ex) { var retVal = string.Empty; switch (ex.ErrorCode) { case 11001: // Host not found. retVal = ex.Message; break; case 10060: //Connection timed out. (invalid portNo) (yahoo,hotmail and indiatimes) case 10061: //Connection refused. case 10013: // Permission denied. from hotmail retVal = "Invalid host or port number"; break; default: retVal = "Invalid host or port number"; break; } throw new Exception(retVal); } } if (_client.Connected) { _stream = _client.GetStream(); if (isSsl) { try { var sslStream = new SslStream(_stream, false, validate ?? ((sender, cert, chain, err) => true)); sslStream.AuthenticateAsClient(host); _stream = sslStream; } catch (Exception) { throw; } } var response = ReadResponse(); ValidateResponse(response); } }