internal void ClientConnectToServerAsync() { if (EnableSSL) { SSLClient.ConnectToServerAsync(ConnectToServerSSLCallback); } else { NoSSLClient.ConnectToServerAsync(ConnectToServerNoSSLCallback); } }
/// <summary> /// Connect Method. Will return if already connected. Will write errors if missing address, port, or unique key/name. /// </summary> public void Connect() { ConnectionCount++; Debug.Console(2, this, "Attempting connect Count:{0}", ConnectionCount); if (IsConnected) { Debug.Console(0, this, Debug.ErrorLogLevel.Notice, "Already connected. Ignoring."); return; } if (IsTryingToConnect) { Debug.Console(0, this, Debug.ErrorLogLevel.Notice, "Already trying to connect. Ignoring."); return; } try { IsTryingToConnect = true; if (RetryTimer != null) { RetryTimer.Stop(); RetryTimer = null; } if (string.IsNullOrEmpty(Hostname)) { Debug.Console(0, this, Debug.ErrorLogLevel.Warning, "DynamicTcpClient: No address set"); return; } if (Port < 1 || Port > 65535) { Debug.Console(0, this, Debug.ErrorLogLevel.Warning, "DynamicTcpClient: Invalid port"); return; } if (string.IsNullOrEmpty(SharedKey) && SharedKeyRequired) { Debug.Console(0, this, Debug.ErrorLogLevel.Warning, "DynamicTcpClient: No Shared Key set"); return; } // clean up previous client if (Client != null) { Cleanup(); } DisconnectCalledByUser = false; Client = new SecureTCPClient(Hostname, Port, BufferSize); Client.SocketStatusChange += Client_SocketStatusChange; if (HeartbeatEnabled) { Client.SocketSendOrReceiveTimeOutInMs = (HeartbeatInterval * 5); } Client.AddressClientConnectedTo = Hostname; Client.PortNumber = Port; // SecureClient = c; //var timeOfConnect = DateTime.Now.ToString("HH:mm:ss.fff"); ConnectFailTimer = new CTimer(o => { Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Connect attempt has not finished after 30sec Count:{0}", ConnectionCount); if (IsTryingToConnect) { IsTryingToConnect = false; //if (ConnectionHasHungCallback != null) //{ // ConnectionHasHungCallback(); //} //SecureClient.DisconnectFromServer(); //CheckClosedAndTryReconnect(); } }, 30000); Debug.Console(2, this, "Making Connection Count:{0}", ConnectionCount); Client.ConnectToServerAsync(o => { Debug.Console(2, this, "ConnectToServerAsync Count:{0} Ran!", ConnectionCount); if (ConnectFailTimer != null) { ConnectFailTimer.Stop(); } IsTryingToConnect = false; if (o.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED) { Debug.Console(2, this, "Client connected to {0} on port {1}", o.AddressClientConnectedTo, o.LocalPortNumberOfClient); o.ReceiveDataAsync(Receive); if (SharedKeyRequired) { WaitingForSharedKeyResponse = true; WaitForSharedKey = new CTimer(timer => { Debug.Console(1, this, Debug.ErrorLogLevel.Warning, "Shared key exchange timer expired. IsReadyForCommunication={0}", IsReadyForCommunication); // Debug.Console(1, this, "Connect attempt failed {0}", c.ClientStatus); // This is the only case where we should call DisconectFromServer...Event handeler will trigger the cleanup o.DisconnectFromServer(); //CheckClosedAndTryReconnect(); //OnClientReadyForcommunications(false); // Should send false event }, 15000); } else { //CLient connected and shared key is not required so just raise the ready for communication event. if Shared key //required this is called by the shared key being negotiated if (IsReadyForCommunication == false) { OnClientReadyForcommunications(true); // Key not required } } } else { Debug.Console(1, this, "Connect attempt failed {0}", o.ClientStatus); CheckClosedAndTryReconnect(); } }); } catch (Exception ex) { Debug.Console(0, this, Debug.ErrorLogLevel.Error, "Client connection exception: {0}", ex.Message); IsTryingToConnect = false; CheckClosedAndTryReconnect(); } }
/// <summary> /// Establishes a connection with the Broker /// </summary> public void Connect() { CrestronLogger.WriteToLog("MQTTCLIENT - Connect , attempting connection to " + MqttSettings.Instance.IPAddressOfTheServer.ToString(), 1); tcpClient.ConnectToServerAsync(ConnectToServerCallback); }
public void Connect(string args_str) { if (client != null && client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED) { CrestronConsole.ConsoleCommandResponse("Client is already connected. Disconnect first"); return; } // Parse command-line arguments // You can optionally associate the client object with a certifiate and private key, which both must be in DER format, from the file system // For this particular example, the filenames must not contains spaces and must be located in the application directory string[] args = args_str.Split(' '); if (args.Length != 2 && args.Length != 4) { CrestronConsole.ConsoleCommandResponse("usage: connect [<cert_file> <key_file>] <hostname> <port>"); return; } bool provideCert = false; string cert_fn = null; // certificate filename string key_fn = null; // private key filename int start = 0; // starting index of the hostname and port arguments in args if (args.Length == 4) // user provides filenames for the cert/key before the hostname and port arguments. { provideCert = true; cert_fn = args[0]; key_fn = args[1]; start += 2; } string server_hostname = args[start]; int port = 0; try { port = int.Parse(args[start + 1]); } catch { CrestronConsole.ConsoleCommandResponse("Error: port number passed in is not numeric"); return; } if (port > 65535 || port < 0) { CrestronConsole.ConsoleCommandResponse("Port number is out of range\r\n"); return; } int bufsize = 100; // This is simply a hard-coded buffer size for this example if (client == null) { PrintAndLog("Instantiating a new client object..."); try { client = new SecureTCPClient(server_hostname, port, bufsize); client.SocketStatusChange += new SecureTCPClientSocketStatusChangeEventHandler(clientSocketStatusChange); } catch (Exception e) { PrintAndLog("Error encountered while instantiating the client object: " + e.Message); return; } } // client object already exists; just update the destination hostname/port. // This allows to user to simply run connect again if the connection fails, possibly trying a new host/port else { client.AddressClientConnectedTo = server_hostname; client.PortNumber = port; } if (provideCert) { X509Certificate cert; byte[] key; // Populate cert and key loadCertAndKey(cert_fn, key_fn, out cert, out key); // Set the client's certificate and private key /* * The X509Certificate passed to SetClientCertificate should have the following attributes in these extension * fields: * * [...] * X509v3 Basic Constraints: critical * CA:FALSE * X509v3 Key Usage: critical * Digital Signature, Key Encipherment, Key Agreement * X509v3 Extended Key Usage: * TLS Web Client Authentication, TLS Web Server Authentication * [...] */ // Only call SetClientCertificate and SetClientPrivateKey if loadCertAndKey succeeded in populating cert and key. // Otherwise, the client will be associated with a default key and certificate determined by the control system's SSL settings if (cert != null && key != null) { PrintAndLog("Associating user-specified certificate and key with client..."); client.SetClientCertificate(cert); // The user-provided private key set here must correspond to the public key embedded in the client's certificate client.SetClientPrivateKey(key); } else { PrintAndLog("Associating default certificate and key with client..."); } } SocketErrorCodes err; ErrorLog.Notice("Trying to connect with server..."); try { // clientConnectCallback gets invoked once client either // connects successfully or encounters an error err = client.ConnectToServerAsync(clientConnectCallback); PrintAndLog("ConnectToServerAsync returned: " + err); } catch (Exception e) { PrintAndLog("Error connecting to server: " + e.Message); } }