コード例 #1
0
 private void ConnectToServerCallback(SecureTCPClient myTCPClient)
 {
     try
     {
         if (myTCPClient.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED)
         {
             MqttMsgConnect connect = MsgBuilder.BuildConnect(this.ClientId, MqttSettings.Instance.Username, MqttSettings.Instance.Password, this.WillRetain,
                                                              this.WillQosLevel, this.WillFlag, this.WillTopic, this.WillMessage, this.CleanSession, this.KeepAlivePeriod, ProtocolVersion);
             Send(connect);
             //TODO: timer for connack
             tcpClient.ReceiveData();
             MqttMsgBase packet = PacketDecoder.DecodeControlPacket(tcpClient.IncomingDataBuffer);
             if (packet.Type == MqttMsgBase.MQTT_MSG_CONNACK_TYPE)
             {
                 RouteControlPacketToMethodHandler(packet);
             }
             else
             {
                 throw new MqttConnectionException("MQTTCLIENT - ConnectToServerCallback - " + PayloadMapper.ClientType + " , Expected CONNACK , received " + packet, new ArgumentException());
             }
         }
     }
     catch (MqttClientException e)
     {
         CrestronLogger.WriteToLog("MQTTCLIENT - ConnectToServerCallback - Error occured : " + e.ErrorCode, 7);
         CrestronLogger.WriteToLog("MQTTCLIENT - ConnectToServerCallback - Error occured : " + e.StackTrace, 7);
     }
     catch (Exception e)
     {
         CrestronLogger.WriteToLog("MQTTCLIENT - ConnectToServerCallback - Error occured : " + e.Message, 7);
         CrestronLogger.WriteToLog("MQTTCLIENT - ConnectToServerCallback - Error occured : " + e.StackTrace, 7);
         //Disconnect from server , signal error at module lvl;
     }
 }
コード例 #2
0
        /// <summary>
        /// SocketStatusChange Callback
        /// </summary>
        /// <param name="client"></param>
        /// <param name="clientSocketStatus"></param>
        void Client_SocketStatusChange(SecureTCPClient client, SocketStatus clientSocketStatus)
        {
            if (ProgramIsStopping)
            {
                ProgramIsStopping = false;
                return;
            }
            try
            {
                Debug.Console(2, this, "Socket status change: {0} ({1})", client.ClientStatus, (ushort)(client.ClientStatus));

                OnConnectionChange();
                // The client could be null or disposed by this time...
                if (Client == null || Client.ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED)
                {
                    HeartbeatStop();
                    OnClientReadyForcommunications(false); // socket has gone low
                    CheckClosedAndTryReconnect();
                }
            }
            catch (Exception ex)
            {
                Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Error in socket status change callback. Error: {0}\r\r{1}", ex, ex.InnerException);
            }
        }
 public SecureClient()
 {
     CrestronConsole.AddNewConsoleCommand(this.Connect, "connect", "usage: connect [<cert_file> <key_file>] <hostname> <port>", ConsoleAccessLevelEnum.AccessOperator);
     CrestronConsole.AddNewConsoleCommand(this.SendMessage, "send", "send <msg>", ConsoleAccessLevelEnum.AccessOperator);
     CrestronConsole.AddNewConsoleCommand(this.Disconnect, "disconnect", "disconnect from server if currently connected", ConsoleAccessLevelEnum.AccessOperator);
     CrestronConsole.AddNewConsoleCommand(this.ShowStatus, "showstatus", "show the client socket's current status", ConsoleAccessLevelEnum.AccessOperator);
     client = null;
 }
 public void clientSendCallback(SecureTCPClient client, int bytesSent)
 {
     if (bytesSent <= 0) // 0 or negative byte count indicates the connection has been closed
     {
         PrintAndLog("clientSendCallback: Could not send message- connection closed");
     }
     else
     {
         CrestronConsole.PrintLine("clientSendCallback: Sent " + bytesSent + " bytes to " + client.AddressClientConnectedTo + " port " + client.PortNumber);
     }
 }
コード例 #5
0
 public void Initialize(string username, string password, ushort port, string ipAddressOfTheServer, ushort bufferSize, string clientId,
                        ushort willFlag, ushort willReatin, uint willQoS, string willTopic, string willMessage, ushort keepAlivePeriod, ClientType clientType, uint publishQoSLevel,
                        uint retain, uint cleanSession, string certificateFileName, string privateKeyFileName)
 {
     {
         MqttSettings.Instance.Username             = username;
         MqttSettings.Instance.Password             = password;
         MqttSettings.Instance.BufferSize           = Convert.ToInt32(bufferSize);
         MqttSettings.Instance.Port                 = Convert.ToInt32(port);
         MqttSettings.Instance.IPAddressOfTheServer = IPAddress.Parse(ipAddressOfTheServer);
     }
     CrestronLogger.WriteToLog("Settings initialized", 1);
     {
         KeepAlivePeriod = keepAlivePeriod;
         ClientId        = clientId;
         WillFlag        = willFlag == 0 ? false : true;
         WillRetain      = willReatin == 0 ? false : true;
         WillQosLevel    = (byte)willQoS;
         WillTopic       = willTopic;
         WillMessage     = willMessage;
         Topics          = new Dictionary <string, byte>();
         PublishQoSLevel = publishQoSLevel;
         Retain          = retain == 0 ? false : true;
         CleanSession    = cleanSession == 0 ? false : true;
     }
     CrestronLogger.WriteToLog("CLIENT STUFF initialized", 1);
     {
         try
         {
             tcpClient = new SecureTCPClient(ipAddressOfTheServer.ToString(), port, bufferSize);
             if (certificateFileName != "//" && privateKeyFileName != "//")
             {
                 var certificate           = ReadFromResource(@"NVRAM\\" + certificateFileName);
                 X509Certificate2 x509Cert = new X509Certificate2(certificate);
                 tcpClient.SetClientCertificate(x509Cert);
                 tcpClient.SetClientPrivateKey(ReadFromResource(@"NVRAM\\" + privateKeyFileName));
             }
             tcpClient.SocketStatusChange += this.OnSocketStatusChange;
             PayloadMapper                  = new PayloadMapper();
             PayloadMapper.ClientType       = clientType;
             PacketDecoder                  = new PacketDecoder();
             sessionManager                 = new MqttSessionManager(clientId);
             publisherManager               = new MqttPublisherManager(sessionManager);
             publisherManager.PacketToSend += this.OnPacketToSend;
         }
         catch (Exception e)
         {
             OnErrorOccured("ERROR DURING INITIALIZATION: " + e.Message);
         }
     }
     CrestronLogger.WriteToLog("MQTTCLIENT - Initialize - completed : " + clientId, 1);
 }
コード例 #6
0
 private void OnSocketStatusChange(SecureTCPClient myTCPClient, SocketStatus serverSocketStatus)
 {
     CrestronLogger.WriteToLog("MQTTCLIENT - OnSocketStatusChange - " + PayloadMapper.ClientType + " socket status : " + serverSocketStatus, 1);
     if (serverSocketStatus == SocketStatus.SOCKET_STATUS_CONNECTED)
     {
         OnConnectionStateChanged(1);
     }
     else
     {
         OnConnectionStateChanged(0);
         CTimer timer = new CTimer(DisconnectTimerCallback, 5000);
     }
 }
 public void clientConnectCallback(SecureTCPClient client)
 {
     CrestronConsole.PrintLine("clientConnectCallback: ClientStatus is: " + client.ClientStatus);
     if (client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED)
     {
         CrestronConsole.PrintLine("clientConnectCallback: Connected to " + client.AddressClientConnectedTo + " on port " + client.PortNumber);
         // Once connected, begin waiting for packets from the server.
         // This call to ReceiveDataAsync is necessary to receive the FIN packet from the server in the event
         // that the TLS handshake fails and the connection cannot be made. If you do not call ReceiveDataAsync here,
         // the client will remain "connected" from its perspective, though no connection has been made.
         client.ReceiveDataAsync(clientReceiveCallback);
     }
     else
     {
         PrintAndLog("clientConnectCallback: No connection could be made with the server.");
     }
 }
コード例 #8
0
        /// <summary>
        ///  Internal call to close up client. ALWAYS use this when disconnecting.
        /// </summary>
        void Cleanup()
        {
            IsTryingToConnect = false;

            if (Client != null)
            {
                //SecureClient.DisconnectFromServer();
                Debug.Console(2, this, "Disconnecting Client {0}", DisconnectCalledByUser ? ", Called by user" : "");
                Client.SocketStatusChange -= Client_SocketStatusChange;
                Client.Dispose();
                Client = null;
            }
            if (ConnectFailTimer != null)
            {
                ConnectFailTimer.Stop();
                ConnectFailTimer.Dispose();
                ConnectFailTimer = null;
            }
        }
コード例 #9
0
 private void ReceiveCallback(SecureTCPClient myClient, int numberOfBytesReceived)
 {
     try
     {
         if (numberOfBytesReceived != 0)
         {
             byte[] incomingDataBuffer = new byte[numberOfBytesReceived];
             Array.Copy(myClient.IncomingDataBuffer, 0, incomingDataBuffer, 0, numberOfBytesReceived);
             tcpClient.ReceiveDataAsync(ReceiveCallback);
             DecodeMultiplePacketsByteArray(incomingDataBuffer);
         }
     }
     catch (Exception e)
     {
         CrestronLogger.WriteToLog("MQTTCLIENT - ReceiveCallback - Error occured : " + e.InnerException + " " + e.Message, 7);
         CrestronLogger.WriteToLog("MQTTCLIENT - ReceiveCallback - Error occured : " + e.StackTrace, 7);
         OnErrorOccured(e.Message);
         Disconnect(false);
     }
 }
コード例 #10
0
 // This will end the client's TCP connection with the server by sending a FIN message, or
 // notify you that the client socket is already disconnected
 public void Disconnect(string args)
 {
     try
     {
         if (client != null)
         {
             SocketErrorCodes err = client.DisconnectFromServer();
             PrintAndLog("Disconnect with error code: " + err);
             client.Dispose();
             client = null;
         }
         else
         {
             CrestronConsole.ConsoleCommandResponse("Client is already disconnected.");
         }
     }
     catch (Exception e)
     {
         PrintAndLog("Error in Disconnect: " + e.Message);
     }
 }
コード例 #11
0
 public void clientReceiveCallback(SecureTCPClient client, int bytes_recvd)
 {
     if (bytes_recvd <= 0) // 0 or negative byte count indicates the connection has been closed
     {
         PrintAndLog("clientReceiveCallback: Could not receive message- connection closed");
     }
     else
     {
         try
         {
             CrestronConsole.PrintLine("Received " + bytes_recvd + " bytes from " + client.AddressClientConnectedTo + " port " + client.PortNumber);
             string received = ASCIIEncoding.ASCII.GetString(client.IncomingDataBuffer, 0, client.IncomingDataBuffer.Length);
             CrestronConsole.PrintLine("Server says: " + received);
         }
         catch (Exception e)
         {
             PrintAndLog("Exception in clientReceiveCallback: " + e.Message);
         }
         // Wait for another message
         client.ReceiveDataAsync(clientReceiveCallback);
     }
 }
コード例 #12
0
        /// <summary>
        /// Receive callback
        /// </summary>
        /// <param name="client"></param>
        /// <param name="numBytes"></param>
        void Receive(SecureTCPClient client, int numBytes)
        {
            if (numBytes > 0)
            {
                string str     = string.Empty;
                var    handler = TextReceivedQueueInvoke;
                try
                {
                    var bytes = client.IncomingDataBuffer.Take(numBytes).ToArray();
                    str = Encoding.GetEncoding(28591).GetString(bytes, 0, bytes.Length);
                    Debug.Console(2, this, "Client Received:\r--------\r{0}\r--------", str);
                    if (!string.IsNullOrEmpty(checkHeartbeat(str)))
                    {
                        if (SharedKeyRequired && str == "SharedKey:")
                        {
                            Debug.Console(2, this, "Server asking for shared key, sending");
                            SendText(SharedKey + "\n");
                        }
                        else if (SharedKeyRequired && str == "Shared Key Match")
                        {
                            StopWaitForSharedKeyTimer();


                            Debug.Console(2, this, "Shared key confirmed. Ready for communication");
                            OnClientReadyForcommunications(true); // Successful key exchange
                        }
                        else
                        {
                            //var bytesHandler = BytesReceived;
                            //if (bytesHandler != null)
                            //    bytesHandler(this, new GenericCommMethodReceiveBytesArgs(bytes));
                            var textHandler = TextReceived;
                            if (textHandler != null)
                            {
                                textHandler(this, new GenericTcpServerCommMethodReceiveTextArgs(str));
                            }
                            if (handler != null)
                            {
                                MessageQueue.TryToEnqueue(new GenericTcpServerCommMethodReceiveTextArgs(str));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.Console(1, this, "Error receiving data: {1}. Error: {0}", ex.Message, str);
                }
                if (client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED)
                {
                    client.ReceiveDataAsync(Receive);
                }

                //Check to see if there is a subscription to the TextReceivedQueueInvoke event. If there is start the dequeue thread.
                if (handler != null)
                {
                    var gotLock = DequeueLock.TryEnter();
                    if (gotLock)
                    {
                        CrestronInvoke.BeginInvoke((o) => DequeueEvent());
                    }
                }
            }
            else //JAG added this as I believe the error return is 0 bytes like the server. See help when hover on ReceiveAsync
            {
                client.DisconnectFromServer();
            }
        }
コード例 #13
0
ファイル: MqttClient.cs プロジェクト: fasteddy516/SimplMQTT
        public void Initialize(
            string clientID,
            string brokerAddress,
            ushort brokerPort,
            ushort enableSSL,
            string username,
            string password,
            ushort willFlag,
            ushort willRetain,
            uint willQoS,
            string willTopic,
            string willMessage,
            uint cleanSession,
            ushort bufferSize
            )
        {
            MqttSettings.Instance.Username   = username;
            MqttSettings.Instance.Password   = password;
            MqttSettings.Instance.BufferSize = Convert.ToInt32(bufferSize);
            MqttSettings.Instance.Port       = Convert.ToInt32(brokerPort);
            MqttSettings.Instance.Broker     = brokerAddress;
            EnableSSL = (enableSSL > 0);
            CrestronLogger.WriteToLog("Instance Settings initialized", 1);

            KeepAlivePeriod = 0; // currently set to 0, as the keepalive mechanism has not been implemented
            ClientID        = clientID;
            WillFlag        = willFlag == 0 ? false : true;
            WillRetain      = willRetain == 0 ? false : true;
            WillQosLevel    = (byte)willQoS;
            WillTopic       = willTopic;
            WillMessage     = willMessage;
            Subscriptions   = new Dictionary <string, byte>();
            CleanSession    = cleanSession == 0 ? false : true;

            CrestronLogger.WriteToLog("Client settings initialized", 1);

            try
            {
                if (EnableSSL)
                {
                    SSLClient = new SecureTCPClient(brokerAddress.ToString(), brokerPort, bufferSize);
                    if (CertificateFile != "" && KeyFile != "")
                    {
                        var certificate           = ReadFromResource(@"NVRAM\\" + CertificateFile);
                        X509Certificate2 x509Cert = new X509Certificate2(certificate);
                        SSLClient.SetClientCertificate(x509Cert);
                        SSLClient.SetClientPrivateKey(ReadFromResource(@"NVRAM\\" + KeyFile));
                    }
                    SSLClient.SocketStatusChange += this.OnSSLSocketStatusChange;
                }
                else
                {
                    NoSSLClient = new TCPClient(brokerAddress.ToString(), brokerPort, bufferSize);
                    NoSSLClient.SocketStatusChange += this.OnNoSSLSocketStatusChange;
                }
                PacketDecoder    = new PacketDecoder();
                sessionManager   = new MqttSessionManager(clientID);
                publisherManager = new MqttPublisherManager(sessionManager);
                publisherManager.PacketToSend += this.OnPacketToSend;
            }
            catch (Exception e)
            {
                OnErrorOccured("ERROR DURING INITIALIZATION: " + e.Message);
            }

            CrestronLogger.WriteToLog("MQTTCLIENT - Initialize - completed : " + clientID, 1);
        }
コード例 #14
0
        /// <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();
            }
        }
コード例 #15
0
 public void clientSocketStatusChange(SecureTCPClient client, SocketStatus clientSocketStatus)
 {
     PrintAndLog("Client Socket Status Change - Socket State is now " + clientSocketStatus);
 }
コード例 #16
0
ファイル: MqttClient.cs プロジェクト: fasteddy516/SimplMQTT
 private void OnSSLSocketStatusChange(SecureTCPClient myTCPClient, SocketStatus serverSocketStatus)
 {
     OnSocketStatusChange(serverSocketStatus);
 }
コード例 #17
0
ファイル: ControlSystem.cs プロジェクト: clarkp26/SSH_Test
        /// <summary>
        /// ControlSystem Constructor. Starting point for the SIMPL#Pro program.
        /// Use the constructor to:
        /// * Initialize the maximum number of threads (max = 400)
        /// * Register devices
        /// * Register event handlers
        /// * Add Console Commands
        ///
        /// Please be aware that the constructor needs to exit quickly; if it doesn't
        /// exit in time, the SIMPL#Pro program will exit.
        ///
        /// You cannot send / receive data in the constructor
        /// </summary>
        public ControlSystem()
            : base()
        {
            try
            {
                Thread.MaxNumberOfUserThreads = 20;

                //Subscribe to the controller events (System, Program, and Ethernet)
                CrestronEnvironment.SystemEventHandler        += new SystemEventHandler(_ControllerSystemEventHandler);
                CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(_ControllerProgramEventHandler);
                CrestronEnvironment.EthernetEventHandler      += new EthernetEventHandler(_ControllerEthernetEventHandler);

                UcEngine ucEngine = new UcEngine(0x03, this);

                //WebSocketClient webSocketclient = new WebSocketClient
                //{
                //    KeepAlive = false,
                //    VerifyServerCertificate = false,
                //    Port = 443,
                //    //Host = "C4-54B203910FDC"
                //    Host = "10.25.94.48"
                //    //SSL = true
                //};
                //WebSocketClientAsyncConnectCallback webSocketClientAsyncConnectCallback = del;
                //var err = webSocketclient.ConnectEx();
                //ErrorLog.Info("URL: " +(int) err);
                //string send = "reboot";
                //byte[] bytes = Encoding.ASCII.GetBytes(send);
                //System.Security.Cryptography.X509Certificates.X509Certificate x509Certificate = new X509Certificate();
                //Crestron.SimplSharp.Cryptography.X509Certificates.X509Certificate x509Certificate1 = new Crestron.SimplSharp.Cryptography.X509Certificates.X509Certificate(bytes);


                //webSocketclient.SetClientCertificate(x509Certificate1);
                //webSocketclient.Connect();
                ////webSocketClient.Host = "10.25.94.48";
                //ErrorLog.Info("Client Connected: " + webSocketClient.Connected);
                //webSocketClient.Port = 443;
                //webSocketClient.SSL = true;


                //var connectCode = webSocketClient.Connect();

                //ErrorLog.Info("Err Code: " + (int)connectCode);

                //string server = "10.25.94.48";
                //TcpClient client = new TcpClient(server, 41797);
                //SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
                ////ErrorLog.Info("SSL: " + sslStream.SslProtocol);
                string send   = "reboot\r";
                byte[] bytes  = Encoding.ASCII.GetBytes(send);
                string send1  = "reboot";
                byte[] bytes1 = Encoding.ASCII.GetBytes(send1);
                //using (sslStream)
                //{
                //    sslStream.AuthenticateAsClient(server);
                //    ErrorLog.Info("SSL: " + sslStream.SslProtocol);
                //    ErrorLog.Info("Can Write: " + sslStream.CanWrite);
                //    //sslStream.Begi
                //    sslStream.Write(bytes);
                //    ErrorLog.Info("Can Write: " + sslStream.CanWrite);

                // This is where you read and send data
                //}
                //client.Close();



                SecureTCPClient secureTCPClient = new SecureTCPClient("10.25.94.48", 41797, bytes.Length);
                var             err1            = secureTCPClient.ConnectToServer();
                ErrorLog.Info("Secure Error Code after connect: " + (int)err1);
                var sendErr = secureTCPClient.SendData(bytes, bytes.Length);
                ErrorLog.Info("Secure Error Code after Send: " + (int)sendErr);
                ErrorLog.Info("Server Address: " + secureTCPClient.AddressClientConnectedTo);
                ErrorLog.Info("Socket Status: " + (int)secureTCPClient.ClientStatus);


                var sendErr2 = secureTCPClient.SendData(bytes1, bytes1.Length);
                ErrorLog.Info("Secure Error Code after Send2: " + (int)sendErr2);
                var ids = secureTCPClient.DisconnectFromServer();
                ErrorLog.Info("Secure Error Code after Disconnect: " + (int)ids);


                //    TCPClient tCPClient = new TCPClient("10.25.94.48", 41797, 1000);
                //    var err = tCPClient.ConnectToServer();
                //    ErrorLog.Info("Err code: " + (int)err);
                //tCPClient.SendData(bytes,0,1000);
                //    tCPClient.DisconnectFromServer();


                //System.Net.Sockets.TcpClient csnative = new System.Net.Sockets.TcpClient("10.25.94.48", 443);
                //    ErrorLog.Info("Connected: " + csnative.Connected);
                //    SslStream sslStream = new SslStream(csnative.GetStream());
                //    ErrorLog.Info("SSL: " + sslStream.IsAuthenticated);
                //    sslStream.AuthenticateAsClient("10.25.94.24");

                //    ErrorLog.Info("SSL: " + sslStream.SslProtocol);
                //sslStream.AuthenticateAsClient("10.25.94.48");
                //SshClient sshClient = new SshClient("C4-54B203910FDC", 22, "admin", "sfb");
                //sshClient.ErrorOccurred += SshClient_ErrorOccurred1;
                //ErrorLog.Info("Connected? " + (int)tCPClient.ClientStatus);

                //SocketErrorCodes err = tCPClient.ConnectToServer();
                //ErrorLog.Info("SocketErrorCode: " + (int)err);
                //ErrorLog.Info("Connected? " + (int)tCPClient.ClientStatus);

                //sslStream.Write(bytes);
                //tCPClient.SendData(bytes, 0, 1000);
                //SshClient sshClient = new SshClient("C4-54B203910FDC", 4443, "hrav", "2Loughmuck!");
                //sshClient.ErrorOccurred += SshClient_ErrorOccurred;
                //sshClient.Connect();

                //IEnumerable<ForwardedPort> s = sshClient.ForwardedPorts;
                //List<ForwardedPort> list = s.ToList();
                //foreach( var a in list)
                //{
                //    ErrorLog.Info("" + a.IsStarted);

                //}

                //SshClient sshClient = new SshClient("10.25.94.48", 4443, "hrav", "2Loughmuck!");


                //var stream = sshClient.CreateShellStream("terminal", 80, 24, 800, 600, 1024);
                //stream.Write("Reboot");
                //SshCommand sshCommand = new SshCommand();
                //ErrorLog.Info("Connected: " + sshClient.IsConnected);
                //SshCommand cmd = sshClient.RunCommand("info");
                //string res = cmd.Execute();
                //ErrorLog.Info("Response: " + res);
            }
            catch (Exception e)
            {
                //if(e.GetType == SshConnectionException)
                //ErrorLog.Info("Errrrrr : " + (int)e.DisconnectReason);
                ErrorLog.Error("Error in the constructor: {0}", e.Message);
                ErrorLog.Error("Error in the constructor: {0}", e.InnerException);
                ErrorLog.Error("Error in the constructor: {0}", e.ToString());
                //ErrorLog.Error("Error in the constructor: {0}", e.Data);
            }
        }
コード例 #18
0
 private void SendCallback(SecureTCPClient myTCPClient, int numberOfBytesSent)
 {
     ;
 }
コード例 #19
0
        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);
            }
        }
コード例 #20
0
ファイル: MqttClient.cs プロジェクト: fasteddy516/SimplMQTT
 private void ConnectToServerSSLCallback(SecureTCPClient myTCPClient)
 {
     ConnectToServerCallback();
 }
コード例 #21
0
ファイル: MqttClient.cs プロジェクト: fasteddy516/SimplMQTT
 private void ClientSendSSLCallback(SecureTCPClient myTCPClient, int numberOfBytesSent)
 {
 }
コード例 #22
0
ファイル: MqttClient.cs プロジェクト: fasteddy516/SimplMQTT
 private void ClientReceiveSSLCallback(SecureTCPClient myTCPClient, int numberOfBytesReceived)
 {
     ReceiveCallback(numberOfBytesReceived);
 }