// 接收消息
        private void MessageReceived(NetworkingPlayer player, Text frame, NetWorker sender)
        {
            try
            {
                JSONNode data = JSONNode.Parse(frame.ToString());

                if (data["register"] != null)
                {
                    Register(player, data["register"]);
                }
                else if (data["update"] != null)
                {
                    Update(player, data["update"]);
                }
                else if (data["get"] != null)
                {
                    Get(player, data["get"]);
                }
            }
            catch
            {
                // Ignore the message and disocnnect the requester
                server.Disconnect(player, true);
            }
        }
예제 #2
0
 /// <summary>
 /// Disconnects Client
 /// </summary>
 /// <param name="client"></param>
 public void DisconnectClient(uint client)
 {
     try
     {
         myTcpServer.Disconnect(client);
         Debug.Console(2, this, Debug.ErrorLogLevel.Notice, "Disconnected client index: {0}", client);
     }
     catch (Exception ex)
     {
         Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error Disconnecting client index: {0}. Error: {1}", client, ex);
     }
 }
예제 #3
0
        /// <summary>
        /// Secure Received Data Async Callback
        /// </summary>
        /// <param name="mySecureTCPServer"></param>
        /// <param name="clientIndex"></param>
        /// <param name="numberOfBytesReceived"></param>
        void TcpServerReceivedDataAsyncCallback(TCPServer myTCPServer, uint clientIndex, int numberOfBytesReceived)
        {
            if (numberOfBytesReceived > 0)
            {
                string received = "Nothing";
                try
                {
                    byte[] bytes = myTCPServer.GetIncomingDataBufferForSpecificClient(clientIndex);
                    received = System.Text.Encoding.GetEncoding(28591).GetString(bytes, 0, numberOfBytesReceived);
                    if (WaitingForSharedKey.Contains(clientIndex))
                    {
                        received = received.Replace("\r", "");
                        received = received.Replace("\n", "");
                        if (received != SharedKey)
                        {
                            byte[] b = Encoding.GetEncoding(28591).GetBytes("Shared key did not match server. Disconnecting");
                            Debug.Console(1, this, Debug.ErrorLogLevel.Warning, "Client at index {0} Shared key did not match the server, disconnecting client. Key: {1}", clientIndex, received);
                            myTCPServer.SendData(clientIndex, b, b.Length);
                            myTCPServer.Disconnect(clientIndex);
                            return;
                        }

                        WaitingForSharedKey.Remove(clientIndex);
                        byte[] success = Encoding.GetEncoding(28591).GetBytes("Shared Key Match");
                        myTCPServer.SendDataAsync(clientIndex, success, success.Length, null);
                        OnServerClientReadyForCommunications(clientIndex);
                        Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Client with index {0} provided the shared key and successfully connected to the server", clientIndex);
                    }

                    else if (!string.IsNullOrEmpty(checkHeartbeat(clientIndex, received)))
                    {
                        onTextReceived(received, clientIndex);
                    }
                }
                catch (Exception ex)
                {
                    Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error Receiving data: {0}. Error: {1}", received, ex);
                }
                if (myTCPServer.GetServerSocketStatusForSpecificClient(clientIndex) == SocketStatus.SOCKET_STATUS_CONNECTED)
                {
                    myTCPServer.ReceiveDataAsync(clientIndex, TcpServerReceivedDataAsyncCallback);
                }
            }
            else
            {
                // If numberOfBytesReceived <= 0
                myTCPServer.Disconnect();
            }
        }
예제 #4
0
        public void ServerDataReceivedCallback(TCPServer 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 ----------");
            }
        }
예제 #5
0
        private void SocketOnSocketStatusChange(TCPServer myTcpServer, uint clientIndex, SocketStatus serverSocketStatus)
        {
            if (_connections == null)
            {
                _connections = new Dictionary <uint, SocketStatus>();
            }

            CloudLog.Debug("{0} Connection Status for ClientIndex {1}, {2}", GetType().Name, clientIndex, serverSocketStatus);

            _connections[clientIndex] = serverSocketStatus;

            if (serverSocketStatus != SocketStatus.SOCKET_STATUS_CONNECTED)
            {
                return;
            }

            if (_threads == null)
            {
                _threads = new Dictionary <uint, Thread>();
            }

            if (!_threads.ContainsKey(clientIndex) ||
                _threads[clientIndex].ThreadState != Thread.eThreadStates.ThreadRunning)
            {
                try
                {
                    _threads[clientIndex] = new Thread(ReceiveHandler, clientIndex)
                    {
                        Name     = string.Format("{0} Rx Handler for client index {1}", GetType().Name, clientIndex),
                        Priority = Thread.eThreadPriority.HighPriority
                    };
                }
                catch (Exception e)
                {
                    CloudLog.Exception(e, "Error starting RX Handler thread for client index {0}", clientIndex);
                    _socket.Disconnect(clientIndex);
                }
            }
        }
예제 #6
0
 /// <summary>
 /// Unsecure Received Data Async Callback
 /// </summary>
 /// <param name="myTCPServer"></param>
 /// <param name="clientIndex"></param>
 /// <param name="numberOfBytesReceived"></param>
 void UnsecureReceivedDataAsyncCallback(TCPServer myTCPServer, uint clientIndex, int numberOfBytesReceived)
 {
     if (numberOfBytesReceived > 0)
     {
         string received = "Nothing";
         byte[] bytes    = myTCPServer.GetIncomingDataBufferForSpecificClient(clientIndex);
         received = System.Text.Encoding.GetEncoding(28591).GetString(bytes, 0, numberOfBytesReceived);
         if (WaitingForSharedKey.Contains(clientIndex))
         {
             received = received.Replace("\r", "");
             received = received.Replace("\n", "");
             if (received != SharedKey)
             {
                 byte[] b = Encoding.GetEncoding(28591).GetBytes("Shared key did not match server. Disconnecting");
                 Debug.Console(2, "Client at index {0} Shared key did not match the server, disconnecting client", clientIndex);
                 ErrorLog.Error("Client at index {0} Shared key did not match the server, disconnecting client", clientIndex);
                 myTCPServer.SendDataAsync(clientIndex, b, b.Length, null);
                 myTCPServer.Disconnect(clientIndex);
             }
             if (myTCPServer.NumberOfClientsConnected > 0)
             {
                 myTCPServer.ReceiveDataAsync(UnsecureReceivedDataAsyncCallback);
             }
             WaitingForSharedKey.Remove(clientIndex);
             byte[] skResponse = Encoding.GetEncoding(28591).GetBytes("Shared Key Match, Connected and ready for communication");
             myTCPServer.SendDataAsync(clientIndex, skResponse, skResponse.Length, null);
             myTCPServer.ReceiveDataAsync(UnsecureReceivedDataAsyncCallback);
         }
         else
         {
             myTCPServer.ReceiveDataAsync(UnsecureReceivedDataAsyncCallback);
             Debug.Console(2, "Secure Server Listening on Port: {0}, client IP: {1}, NumberOfBytesReceived: {2}, Received: {3}\r\n",
                           myTCPServer.PortNumber, myTCPServer.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex), numberOfBytesReceived, received);
             onTextReceived(received);
         }
         checkHeartbeat(clientIndex, received);
     }
     if (myTCPServer.GetServerSocketStatusForSpecificClient(clientIndex) == SocketStatus.SOCKET_STATUS_CONNECTED)
     {
         myTCPServer.ReceiveDataAsync(clientIndex, UnsecureReceivedDataAsyncCallback);
     }
 }
예제 #7
0
        void HeartbeatTimer_CallbackFunction(object o)
        {
            uint clientIndex = (uint)o;

            string address = Secure ? SecureServer.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex) :
                             UnsecureServer.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex);

            ErrorLog.Error("Heartbeat not received for Client at IP: {0}, DISCONNECTING BECAUSE HEARTBEAT REQUIRED IS TRUE", address);
            Debug.Console(2, "Heartbeat not received for Client at IP: {0}, DISCONNECTING BECAUSE HEARTBEAT REQUIRED IS TRUE", address);

            SendTextToClient("Heartbeat not received by server, closing connection", clientIndex);

            if (Secure)
            {
                SecureServer.Disconnect(clientIndex);
            }
            else
            {
                UnsecureServer.Disconnect(clientIndex);
            }
            HeartbeatTimerDictionary.Remove(clientIndex);
        }
예제 #8
0
        /// <summary>
        /// The callback for receiving data from the insecure server client.
        /// </summary>
        /// <param name="server">The server the callback is executed on.</param>
        /// <param name="clientIndex">The index of the client data is received from.</param>
        /// <param name="count">The number of bytes of data received.</param>
        private void ReceiveDataCallback(TCPServer server, uint clientIndex, int count)
        {
            if (count <= 0)
            {
                if (server.ClientConnected(clientIndex))
                {
                    server.ReceiveDataAsync(clientIndex, ReceiveDataCallback);
                }

                return;
            }

            var dataBuffer = server.GetIncomingDataBufferForSpecificClient(clientIndex);
            var data       = Encoding.UTF8.GetString(dataBuffer, 0, count);

            if (Regex.IsMatch(data, "^GET", RegexOptions.IgnoreCase))
            {
                var key = Regex.Match(data, "Sec-WebSocket-Key: (.*)").Groups[1].Value.Trim();
                key = key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
                byte[] keySha1 = Crestron.SimplSharp.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(key));
                string sha64   = Convert.ToBase64String(keySha1);

                var responseMessage = "HTTP/1.1 101 Switching Protocols\r\n" +
                                      "Connection: Upgrade\r\n" +
                                      "Upgrade: websocket\r\n" +
                                      "Sec-WebSocket-Accept: " + sha64 + "\r\n\r\n";

                this.Send(responseMessage, clientIndex, false);
            }
            else
            {
                CrestronConsole.PrintLine("Received '{0}' bytes.", count);
                bool  fin        = (dataBuffer[0] & 128) != 0;
                bool  mask       = (dataBuffer[1] & 128) != 0;
                int   opcode     = dataBuffer[0] & 15;
                ulong dataLength = (ulong)(dataBuffer[1] - 128);
                ulong offset     = 2;

                if (opcode == 0x0)
                {
                    CrestronConsole.PrintLine("Received continuation frame opcode.");
                }
                else if (opcode == 0x1)
                {
                    CrestronConsole.PrintLine("Received text frame opcode.");
                }
                else if (opcode == 0x2)
                {
                    CrestronConsole.PrintLine("Received binary frame opcode.");
                }
                else if (opcode >= 0x3 && opcode <= 0x7)
                {
                    CrestronConsole.PrintLine("Received reserved non-control opcode.");
                }
                else if (opcode == 0x8)
                {
                    this.Send(new byte[]
                    {
                        BitConverter.GetBytes(0x88)[0],
                        BitConverter.GetBytes(0x00)[0]
                    }, clientIndex, false);
                    server.Disconnect(clientIndex);
                    CrestronConsole.PrintLine("Received disconnect OpCode. Disconnected.");
                    return;
                }
                else if (opcode == 0x9)
                {
                    this.Send(new byte[]
                    {
                        BitConverter.GetBytes(0x8A)[0],
                        BitConverter.GetBytes(0x00)[0]
                    }, clientIndex, false);
                    CrestronConsole.PrintLine("Received Ping and sent a Pong.");

                    if (server.ClientConnected(clientIndex))
                    {
                        server.ReceiveDataAsync(clientIndex, ReceiveDataCallback);
                    }

                    return;
                }
                else if (opcode == 0xA)
                {
                    CrestronConsole.PrintLine("Received Pong.");
                    if (server.ClientConnected(clientIndex))
                    {
                        server.ReceiveDataAsync(clientIndex, ReceiveDataCallback);
                    }

                    return;
                }
                else if (opcode >= 0xB && opcode <= 0xF)
                {
                    CrestronConsole.PrintLine("Received reserved control frame opcode.");
                }

                if (dataLength == 126)
                {
                    CrestronConsole.PrintLine("Data length is 126.");
                    dataLength = BitConverter.ToUInt16(new byte[] { dataBuffer[3], dataBuffer[2] }, 0);
                    offset     = 4;
                }
                else if (dataLength == 127)
                {
                    CrestronConsole.PrintLine("Data length is 127.");
                    dataLength = BitConverter.ToUInt64(new byte[] { dataBuffer[9], dataBuffer[8], dataBuffer[7], dataBuffer[6], dataBuffer[5], dataBuffer[4], dataBuffer[3], dataBuffer[2] }, 0);
                    offset     = 10;
                }

                if (dataLength == 0)
                {
                    CrestronConsole.PrintLine("Data length was zero.");
                    this.Send(string.Format("{0}>", InitialParametersClass.ControllerPromptName), clientIndex, true);
                }
                else if (mask)
                {
                    byte[] de = new byte[dataLength];
                    byte[] mk = new byte[4] {
                        dataBuffer[offset], dataBuffer[offset + 1], dataBuffer[offset + 2], dataBuffer[offset + 3]
                    };
                    offset += 4;

                    for (ulong i = 0; i < dataLength; i++)
                    {
                        de[i] = (byte)(dataBuffer[offset + i] ^ mk[i % 4]);
                    }

                    var text = Encoding.UTF8.GetString(de, 0, de.Length);
                    var dr   = DataReceived;
                    if (dr != null)
                    {
                        dr.Invoke(text, clientIndex);
                    }
                }
                else
                {
                    CrestronConsole.PrintLine("Data length was '{0}', but mask bit not set. Invalid message received.", dataLength);
                }
            }

            if (server.ClientConnected(clientIndex))
            {
                server.ReceiveDataAsync(clientIndex, ReceiveDataCallback);
            }
        }
예제 #9
0
 /**
  * Method: replyAndEndConnection
  * Access: private
  * @return: void
  * @param: string _msg
  * @param: uint _cli
  * Description: Encodes and transmits string _msg to connected client _cli, then disconnects the client and
  *              listens for a new connection.
  */
 private void replyAndEndConnection(string _msg, uint _cli)
 {
     Server.SendData(_cli, Encoding.ASCII.GetBytes(_msg), _msg.Length);
     Server.Disconnect(_cli);
     Server.WaitForConnectionAsync(new TCPServerClientConnectCallback(clientConnectHandler));
 }
예제 #10
0
 private void ServerClose(uint clientIndex)
 {
     _server.Disconnect(clientIndex);
 }
예제 #11
0
        public void ReceiveCallback(TCPServer server, uint clientIndex, int bytesReceived, object obj)
        {
            new Thread((o) =>
            {
                string message = Encoding.ASCII.GetString(server.GetIncomingDataBufferForSpecificClient(clientIndex), 0, bytesReceived);

                ErrorLog.Notice("server received {0} bytes from client\r\n{1}", bytesReceived, message);

                if (Regex.IsMatch(message, "^temp:ambient", RegexOptions.IgnoreCase))
                {
                    Match temp = Regex.Match(message, @"(?<=temp:ambient:)\d+", RegexOptions.IgnoreCase);
                    system.TempControl.ambient(int.Parse(temp.Value));
                }
                if (Regex.IsMatch(message, "^drop:client", RegexOptions.IgnoreCase))
                {
                    Match client = Regex.Match(message, @"(?<=drop:client:)\d+", RegexOptions.IgnoreCase);
                    server.Disconnect(uint.Parse(client.Value));
                }

                /*else if (Regex.IsMatch(message, "^temp:", RegexOptions.IgnoreCase))
                 * {
                 *  string action = Regex.Match(message, @"(?<=temp:)\w+", RegexOptions.IgnoreCase).Value;
                 *  system.TempControl.GetType().GetMethod(action).Invoke(system.TempControl, null);
                 * }
                 * else if (Regex.IsMatch(message, "^garage:", RegexOptions.IgnoreCase))
                 * {
                 *  string action = Regex.Match(message, @"(?<=garage:)\w+", RegexOptions.IgnoreCase).Value;
                 *  action = Regex.Replace(action, "open|close", "toggle");
                 *  system.GarageControl.GetType().GetMethod(action).Invoke(system.GarageControl, null);
                 * }*/

                switch (message)
                {
                case "garage:open":
                case "garage:close":
                    system.GarageControl.toggle();
                    break;

                case "garage:release":
                    system.GarageControl.release();
                    break;

                case "temp:raise":
                    system.TempControl.raise();
                    break;

                case "temp:lower":
                    system.TempControl.lower();
                    break;

                case "temp:on":
                    system.TempControl.on();
                    break;

                case "temp:off":
                    system.TempControl.off();
                    break;
                }

                server.ReceiveDataAsync(clientIndex, ReceiveCallback, null);
                return(clientIndex);
            }, null);
        }
예제 #12
0
 public void NotifyClients(string data)
 {
     byte[] buffer = Encoding.ASCII.GetBytes(data);
     try
     {
         new Thread((o) =>
         {
             foreach (var client in clients)
             {
                 if (server.ClientConnected(client.Key))
                 {
                     server.SendDataAsync(client.Key, buffer, buffer.Length, null);
                 }
                 else
                 {
                     ErrorLog.Notice("Client {0} Disconnection Status: {1}", client.Key, server.Disconnect(client.Key));
                     clients.Remove(client.Key);
                 }
             }
             return(clients);
         }, null);
     }
     catch (Exception ex)
     {
         ErrorLog.Notice("Something Went Wrong While Trying To Send Data To Client\r\n{1}", ex.Message);
     }
 }
예제 #13
0
 public void DisposeServer()
 {
     server.Disconnect(false);
     WaitFor(() => { return(!server.IsBound); });
 }
예제 #14
0
 public void Disconnect(Socket socket) => server.Disconnect(socket);