public void ServerDataReceivedCallback(SecureTCPServer server, uint clientIndex, int bytesReceived) { if (bytesReceived <= 0) { CrestronConsole.PrintLine("ServerDataReceivedCallback error: server's connection with client " + clientIndex + " has been closed."); server.Disconnect(clientIndex); // A connection has closed, so another client may connect if the server stopped listening // due to the maximum number of clients connecting if ((server.State & ServerState.SERVER_NOT_LISTENING) > 0) { server.WaitForConnectionAsync(ServerConnectedCallback); } } else { CrestronConsole.PrintLine("\n------ incoming message -----------"); byte[] recvd_bytes = new byte[bytesReceived]; // Copy the received bytes into a local buffer so that they can be echoed back. // Do not pass the reference to the incoming data buffer itself to the SendDataAsync method Array.Copy(server.GetIncomingDataBufferForSpecificClient(clientIndex), recvd_bytes, bytesReceived); // The server in this example expects ASCII text from the client, but any other encoding is possible string recvd_msg = ASCIIEncoding.ASCII.GetString(recvd_bytes, 0, bytesReceived); CrestronConsole.PrintLine("Client " + clientIndex + " says: " + recvd_msg + "\r\nEchoing back to client " + clientIndex + "..."); // echo the received message back to the client who sent it server.SendDataAsync(clientIndex, recvd_bytes, recvd_bytes.Length, ServerDataSentCallback); // Begin waiting for another message from that same client server.ReceiveDataAsync(clientIndex, ServerDataReceivedCallback); CrestronConsole.PrintLine("---------- end of message ----------"); } }
/// <summary> /// Start listening on the specified port /// </summary> public void Listen() { ServerCCSection.Enter(); try { if (Port < 1 || Port > 65535) { Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Server '{0}': Invalid port", Key); ErrorLog.Warn(string.Format("Server '{0}': Invalid port", Key)); return; } if (string.IsNullOrEmpty(SharedKey) && SharedKeyRequired) { Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Server '{0}': No Shared Key set", Key); ErrorLog.Warn(string.Format("Server '{0}': No Shared Key set", Key)); return; } if (SecureServer == null) { SecureServer = new SecureTCPServer(Port, MaxClients); if (HeartbeatRequired) { SecureServer.SocketSendOrReceiveTimeOutInMs = (this.HeartbeatRequiredIntervalMs * 5); } SecureServer.HandshakeTimeout = 30; SecureServer.SocketStatusChange += new SecureTCPServerSocketStatusChangeEventHandler(SecureServer_SocketStatusChange); } else { SecureServer.PortNumber = Port; } ServerStopped = false; // Start the listner SocketErrorCodes status = SecureServer.WaitForConnectionAsync(IPAddress.Any, SecureConnectCallback); if (status != SocketErrorCodes.SOCKET_OPERATION_PENDING) { Debug.Console(0, this, Debug.ErrorLogLevel.Error, "Error starting WaitForConnectionAsync {0}", status); } else { ServerStopped = false; } OnServerStateChange(SecureServer.State); Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Secure Server Status: {0}, Socket Status: {1}", SecureServer.State, SecureServer.ServerSocketStatus); ServerCCSection.Leave(); } catch (Exception ex) { ServerCCSection.Leave(); ErrorLog.Error("{1} Error with Dynamic Server: {0}", ex.ToString(), Key); } }
public ServerBase(List <MqttClient> clients, SessionManager sessionManager, List <ushort> packetIdentifiers, Random rand, int port, int numberOfConnections) { Clients = clients; SessionManager = sessionManager; PacketIdentifiers = packetIdentifiers; Rand = rand; this.Port = port; this.NumberOfConnections = numberOfConnections; Server = new SecureTCPServer(port, 4096, EthernetAdapterType.EthernetLANAdapter, numberOfConnections); Server.SocketStatusChange += OnSocketStatusChange; Server.WaitForConnectionAsync(IPAddress.Parse("0.0.0.0"), this.ConnectionCallback); }
public void ServerConnectedCallback(SecureTCPServer server, uint clientIndex) { if (clientIndex != 0) { CrestronConsole.PrintLine("Server listening on port " + server.PortNumber + " has connected with a client (client #" + clientIndex + ")"); server.ReceiveDataAsync(clientIndex, ServerDataReceivedCallback); if (server.MaxNumberOfClientSupported == server.NumberOfClientsConnected) { CrestronConsole.PrintLine("Client limit reached."); // This call to Stop() causes the server.State flag, SERVER_NOT_LISTENING, to be set server.Stop(); CrestronConsole.PrintLine("After calling server.Stop(), the server state is: " + server.State); } // If the client limit is reached, WaitForConnectionAsync will return SOCKET_MAX_CONNECTIONS_REACHED // and the ServerConnectedCallback will not be registered. Otherwise, the call to WaitForConnectionAsync // causes the server to keep listening for more clients. SocketErrorCodes err = server.WaitForConnectionAsync(ServerConnectedCallback); PrintAndLog("WaitForConnectionAsync returned: " + err); } // A clientIndex of 0 could mean that the server is no longer listening, or that the TLS handshake failed when a client tried to connect. // In the case of a TLS handshake failure, wait for another connection so that other clients can still connect else { CrestronConsole.Print("Error in ServerConnectedCallback: "); if ((server.State & ServerState.SERVER_NOT_LISTENING) > 0) { CrestronConsole.PrintLine("Server is no longer listening."); } else { CrestronConsole.PrintLine("Unable to make connection with client."); // This connection failed, but keep waiting for another server.WaitForConnectionAsync(ServerConnectedCallback); } } }
/// <summary> /// Start listening on the specified port /// </summary> public void Listen() { try { if (Port < 1 || Port > 65535) { Debug.Console(1, Debug.ErrorLogLevel.Warning, "GenericSecureTcpClient '{0}': Invalid port", Key); ErrorLog.Warn(string.Format("GenericSecureTcpClient '{0}': Invalid port", Key)); return; } if (string.IsNullOrEmpty(SharedKey) && SharedKeyRequired) { Debug.Console(1, Debug.ErrorLogLevel.Warning, "GenericSecureTcpClient '{0}': No Shared Key set", Key); ErrorLog.Warn(string.Format("GenericSecureTcpClient '{0}': No Shared Key set", Key)); return; } if (IsListening) { return; } if (Secure) { SecureServer = new SecureTCPServer(Port, MaxClients); SecureServer.SocketStatusChange += new SecureTCPServerSocketStatusChangeEventHandler(SecureServer_SocketStatusChange); ServerStopped = false; SecureServer.WaitForConnectionAsync(IPAddress.Any, SecureConnectCallback); onServerStateChange(); Debug.Console(2, "Secure Server Status: {0}, Socket Status: {1}\r\n", SecureServer.State.ToString(), SecureServer.ServerSocketStatus); } else { UnsecureServer = new TCPServer(Port, MaxClients); UnsecureServer.SocketStatusChange += new TCPServerSocketStatusChangeEventHandler(UnsecureServer_SocketStatusChange); ServerStopped = false; UnsecureServer.WaitForConnectionAsync(IPAddress.Any, UnsecureConnectCallback); onServerStateChange(); Debug.Console(2, "Unsecure Server Status: {0}, Socket Status: {1}\r\n", UnsecureServer.State.ToString(), UnsecureServer.ServerSocketStatus); } } catch (Exception ex) { ErrorLog.Error("Error with Dynamic Server: {0}", ex.ToString()); } }
/// <summary> /// Secure TCP Client Connected to Secure Server Callback /// </summary> /// <param name="mySecureTCPServer"></param> /// <param name="clientIndex"></param> void SecureConnectCallback(SecureTCPServer mySecureTCPServer, uint clientIndex) { if (mySecureTCPServer.ClientConnected(clientIndex)) { if (SharedKeyRequired) { byte[] b = Encoding.GetEncoding(28591).GetBytes(SharedKey + "\n"); mySecureTCPServer.SendDataAsync(clientIndex, b, b.Length, SecureSendDataAsyncCallback); Debug.Console(2, "Sent Shared Key to client at {0}", mySecureTCPServer.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex)); } if (HeartbeatRequired) { CTimer HeartbeatTimer = new CTimer(HeartbeatTimer_CallbackFunction, clientIndex, HeartbeatRequiredIntervalMs); HeartbeatTimerDictionary.Add(clientIndex, HeartbeatTimer); } mySecureTCPServer.ReceiveDataAsync(clientIndex, SecureReceivedDataAsyncCallback); if (mySecureTCPServer.State != ServerState.SERVER_LISTENING && MaxClients > 1 && !ServerStopped) { mySecureTCPServer.WaitForConnectionAsync(IPAddress.Any, SecureConnectCallback); } } }
/// <summary> /// Secure TCP Client Connected to Secure Server Callback /// </summary> /// <param name="mySecureTCPServer"></param> /// <param name="clientIndex"></param> void SecureConnectCallback(SecureTCPServer server, uint clientIndex) { try { Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "ConnectCallback: IPAddress: {0}. Index: {1}. Status: {2}", server.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex), clientIndex, server.GetServerSocketStatusForSpecificClient(clientIndex)); if (clientIndex != 0) { if (server.ClientConnected(clientIndex)) { if (!ConnectedClientsIndexes.Contains(clientIndex)) { ConnectedClientsIndexes.Add(clientIndex); } if (SharedKeyRequired) { if (!WaitingForSharedKey.Contains(clientIndex)) { WaitingForSharedKey.Add(clientIndex); } byte[] b = Encoding.GetEncoding(28591).GetBytes("SharedKey:"); server.SendDataAsync(clientIndex, b, b.Length, (x, y, z) => { }); Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Sent Shared Key Request to client at {0}", server.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex)); } else { OnServerClientReadyForCommunications(clientIndex); } if (HeartbeatRequired) { if (!HeartbeatTimerDictionary.ContainsKey(clientIndex)) { HeartbeatTimerDictionary.Add(clientIndex, new CTimer(HeartbeatTimer_CallbackFunction, clientIndex, HeartbeatRequiredIntervalMs)); } } server.ReceiveDataAsync(clientIndex, SecureReceivedDataAsyncCallback); } } else { Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Client attempt faulty."); } } catch (Exception ex) { Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error in Socket Status Connect Callback. Error: {0}", ex); } // Rearm the listner SocketErrorCodes status = server.WaitForConnectionAsync(IPAddress.Any, SecureConnectCallback); if (status != SocketErrorCodes.SOCKET_OPERATION_PENDING) { Debug.Console(0, this, Debug.ErrorLogLevel.Error, "Socket status connect callback status {0}", status); if (status == SocketErrorCodes.SOCKET_CONNECTION_IN_PROGRESS) { // There is an issue where on a failed negotiation we need to stop and start the server. This should still leave connected clients intact. server.Stop(); Listen(); } } }
override protected void ConnectionCallback(SecureTCPServer server, uint clientIndex) { server.ReceiveDataAsync(clientIndex, ConnectionDataCallback); server.WaitForConnectionAsync("0.0.0.0", ConnectionCallback); }
// Console command implementations public void Listen(string args_str) { if (server != null) { CrestronConsole.PrintLine("Server is already online. Disconnect it first"); return; } int bufsize = 100; // sample size for the server sockets' incoming data buffers int max_connections = 3; // sample size for the maximum number of simultaneous server sockets // 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 != 1 && args.Length != 3) { CrestronConsole.PrintLine("usage: listen [<cert_file> <key_file>] <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 == 3) // 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; } int port = 0; try { port = int.Parse(args[start]); } catch { PrintAndLog("Error: port number passed in is not numeric"); return; } if (port > 65535 || port < 0) { CrestronConsole.PrintLine("Port number is out of range"); return; } ErrorLog.Notice("Instantiating server object..."); try { server = new SecureTCPServer(port, bufsize, EthernetAdapterType.EthernetUnknownAdapter, max_connections); server.SocketStatusChange += new SecureTCPServerSocketStatusChangeEventHandler(ServerSocketStatusChanged); } catch (Exception e) { PrintAndLog("Error encountered while instantiating the server object: " + e.Message); return; } if (provideCert) { X509Certificate cert; byte[] key; // Populate cert and key loadCertAndKey(cert_fn, key_fn, out cert, out key); // Set the server's certificate and private key /* * The X509Certificate passed to SetServerCertificate 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 SetServerCertificate and SetServerPrivateKey if loadCertAndKey succeeded in populating cert and key. // Otherwise, the server 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 server..."); server.SetServerCertificate(cert); // The private key set here must correspond to the public key embedded in the server's certificate server.SetServerPrivateKey(key); } else { PrintAndLog("Associating default certificate and key with server..."); } } SocketErrorCodes err; ErrorLog.Notice("Begin listening for clients..."); // ServerConnectedCallback will get invoked once a client either // connects successfully or if the connection encounters an error err = server.WaitForConnectionAsync(ServerConnectedCallback); PrintAndLog("WaitForConnectionAsync returned: " + err); }
/// <summary> /// Secure TCP Client Connected to Secure Server Callback /// </summary> /// <param name="mySecureTCPServer"></param> /// <param name="clientIndex"></param> void SecureConnectCallback(SecureTCPServer server, uint clientIndex) { try { Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "ConnectCallback: IPAddress: {0}. Index: {1}. Status: {2}", server.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex), clientIndex, server.GetServerSocketStatusForSpecificClient(clientIndex)); if (clientIndex != 0) { if (server.ClientConnected(clientIndex)) { if (!ConnectedClientsIndexes.Contains(clientIndex)) { ConnectedClientsIndexes.Add(clientIndex); } if (SharedKeyRequired) { if (!WaitingForSharedKey.Contains(clientIndex)) { WaitingForSharedKey.Add(clientIndex); } byte[] b = Encoding.GetEncoding(28591).GetBytes("SharedKey:"); server.SendDataAsync(clientIndex, b, b.Length, (x, y, z) => { }); Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Sent Shared Key Request to client at {0}", server.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex)); } else { OnServerClientReadyForCommunications(clientIndex); } if (HeartbeatRequired) { if (!HeartbeatTimerDictionary.ContainsKey(clientIndex)) { HeartbeatTimerDictionary.Add(clientIndex, new CTimer(HeartbeatTimer_CallbackFunction, clientIndex, HeartbeatRequiredIntervalMs)); } } server.ReceiveDataAsync(clientIndex, SecureReceivedDataAsyncCallback); } } else { Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Client attempt faulty."); if (!ServerStopped) { server.WaitForConnectionAsync(IPAddress.Any, SecureConnectCallback); return; } } } catch (Exception ex) { Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error in Socket Status Connect Callback. Error: {0}", ex); } //Debug.Console(1, this, Debug.ErrorLogLevel, "((((((Server State bitfield={0}; maxclient={1}; ServerStopped={2}))))))", // server.State, // MaxClients, // ServerStopped); if ((server.State & ServerState.SERVER_LISTENING) != ServerState.SERVER_LISTENING && MaxClients > 1 && !ServerStopped) { Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Waiting for next connection"); server.WaitForConnectionAsync(IPAddress.Any, SecureConnectCallback); } }