Пример #1
0
        private void MonitorIncomingConnection()
        {
            listener.Start();
            while (true)
            {
                try
                {
                    if (Abort)
                    {
                        //Terminating Server and Monitoring Loop
                        listener.Stop();
                        Trace.WriteLine(Name + ": TCP Server Stopped.");
                        DisconnectAllClients();
                        return;
                    }

                    if (!listener.Pending())
                    {
                        Thread.Sleep(10);
                    }
                    else
                    {
                        System.Net.Sockets.TcpClient client = listener.AcceptTcpClient();
                        Trace.WriteLine(Name + ": New Connection Detected...");
                        TcpServerConnectEventArgs eArgs = new TcpServerConnectEventArgs()
                        {
                            Client = client
                        };
                        ClientConnecting?.Invoke(this, eArgs);

                        if (eArgs.Accept)
                        {
                            //Connection Accepted
                            TcpServerConnection newConnection = null;

                            newConnection = new TcpServerConnection(this, client, Certificate);
                            newConnection.MessageDelimiter = MessageDelimiter;
                            Trace.WriteLine(Name + ": Connection Accepted: Client = " + newConnection.ClientIPAddress);
                            newConnection.ClientDisconnected += OnClientDisconnected;
                            lock (ActiveConnections) { ActiveConnections.Add(newConnection); }
                            ClientConnected?.Invoke(this, new TcpServerEventArgs()
                            {
                                Client = newConnection
                            });
                        }
                        else
                        {
                            //Connection Refused
                            Trace.WriteLine(Name + ": Connection Rejected.");
                            client.Close();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Trace.WriteLine("[WARNING] " + Name + ": Exception raised from Connection Monitoring Thread!\n" + ex.Message);
                    continue;
                }
            }
        }
Пример #2
0
        private void WriteExceptionErrorToClient(TcpServerConnection client, Exception ex)
        {
            string returnMsg = TcpAppCommandStatus.ERR + " " + ex.Message;
            TcpAppServerConnection appServerClient = AppClients.FirstOrDefault(x => x.Connection == client);
            string clientName = appServerClient == null?client.ClientIPAddress.ToString() : appServerClient.Name;

            Debug.WriteLine("AppServer[" + clientName + "]-Error: " + returnMsg);
            client.WriteLineToClient(returnMsg);
        }
Пример #3
0
        private void WriteResultToClient(TcpServerConnection client, TcpAppInputCommand input)
        {
            string returnMsg = "#TCP# " + input.Command.Keyword + " " + input.Status.ToString();

            if (!string.IsNullOrEmpty(input.OutputMessage))
            {
                returnMsg += " " + input.OutputMessage;
            }
            client.WriteLineToClient(returnMsg);
        }
        private void WriteResultToClient(TcpServerConnection client, TcpAppInputCommand input)
        {
            string returnMsg = input.Command.Keyword + " " + input.Status.ToString();

            if (!string.IsNullOrEmpty(input.OutputMessage))
            {
                returnMsg += " " + input.OutputMessage;
            }
            System.Diagnostics.Trace.WriteLine("Write To Client: " + returnMsg);
            client.WriteLineToClient(returnMsg);
        }
Пример #5
0
 private TcpAppServerConnection AddClientToAppClientsList(TcpServerConnection client)
 {
     lock (AppClients)
     {
         TcpAppServerConnection result = new TcpAppServerConnection()
         {
             Connection = client, Name = "#" + client.ClientIPAddress.ToString()
         };
         AppClients.Add(result);
         client.ProcessReceivedMessageCallback = Client_ProcessReceivedMessage;
         return(result);
     }
 }
Пример #6
0
        private void OnClientDisconnected(object sender, EventArgs e)
        {
            Trace.WriteLine(Name + ": Client disconnected from server.");
            if (SuppressDisconnectEvent)
            {
                return;
            }
            TcpServerConnection client = sender as TcpServerConnection;

            ClientDisconnected?.Invoke(this, new TcpServerEventArgs()
            {
                Client = client
            });
            client.Dispose();
            ActiveConnections.Remove(client);
        }
Пример #7
0
 internal TcpServerDataEventArgs(TcpServerConnection client, byte[] data, int length)
 {
     Client = client;
     Data   = new byte[length];
     Array.Copy(data, Data, length);
 }
Пример #8
0
        private void MonitorIncomingConnection()
        {
            listener.Start();
            while (true)
            {
                try
                {
                    if (Abort)
                    {
                        //Terminating Server and Monitoring Loop
                        listener.Stop();
                        Trace.WriteLine(Name + ": TCP Server Stopped.");
                        DisconnectAllClients();
                        return;
                    }

                    if (!listener.Pending())
                    {
                        Thread.Sleep(10);
                    }
                    else
                    {
                        System.Net.Sockets.TcpClient client = listener.AcceptTcpClient();
                        Trace.WriteLine(Name + ": New Connection Detected...");

                        if (MaxClients > 0)
                        {
                            //MAX Clients Restriction applied
                            if (Clients.Count >= MaxClients)
                            {
                                //Number of connection exceeds, reject incoming connection.
                                Trace.WriteLine(Name + ": Connection Rejected, exceed MAX allowed clients!");
                                byte[] msgBuffer = Encoding.ASCII.GetBytes("Connection Rejected, exceed MAX allowed clients!\r\n");
                                client.GetStream().Write(msgBuffer, 0, msgBuffer.Length);
                                client.GetStream().Flush();
                                client.Close();
                                continue;
                            }
                        }
                        TcpServerConnectEventArgs eArgs = new TcpServerConnectEventArgs()
                        {
                            Client = client
                        };
                        ClientConnecting?.Invoke(this, eArgs);

                        if (eArgs.Accept)
                        {
                            //Connection Accepted
                            TcpServerConnection newConnection = new TcpServerConnection(this, client)
                            {
                                MessageDelimiter = MessageDelimiter
                            };
                            Trace.WriteLine(Name + ": Connection Accepted: Client = " + newConnection.ClientIPAddress);
                            newConnection.ClientDisconnected += OnClientDisconnected;
                            lock (ActiveConnections) { ActiveConnections.Add(newConnection); }
                            ClientConnected?.Invoke(this, new TcpServerEventArgs()
                            {
                                Client = newConnection
                            });
                        }
                        else
                        {
                            //Connection Refused
                            Trace.WriteLine(Name + ": Connection Rejected.");
                            client.Close();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Trace.WriteLine("[WARNING] " + Name + ": Exception raised from Connection Monitoring Thread!\n" + ex.Message);
                    continue;
                }
            }
        }
Пример #9
0
 internal BytesReceivedEventArgs(TcpServerConnection client, byte[] data, int length)
 {
     Client        = client;
     ReceivedBytes = new byte[length];
     Array.Copy(data, ReceivedBytes, length);
 }
Пример #10
0
        private void MonitorIncomingConnection()
        {
            listener.Start();
            while (true)
            {
                try
                {
                    if (Abort)
                    {
                        //Terminating Server and Monitoring Loop
                        listener.Stop();
                        Trace.WriteLine(Name + ": TCP Server Stopped.");
                        DisconnectAllClients();
                        return;
                    }

                    if (!listener.Pending())
                    {
                        Thread.Sleep(10);
                    }
                    else
                    {
                        System.Net.Sockets.TcpClient client = listener.AcceptTcpClient();

                        var stream = client.GetStream();

                        byte[] wsData = null;

                        Thread.Sleep(10); // 停10ms,否则获取握手时数据有可能取不到

                        if (stream.DataAvailable)
                        {
                            var buffer  = new byte[client.ReceiveBufferSize];
                            var factLen = stream.Read(buffer, 0, buffer.Length);
                            wsData = new byte[factLen];
                            Array.Copy(buffer, wsData, factLen);
                        }

                        Trace.WriteLine(Name + ": New Connection Detected...");
                        TcpServerConnectEventArgs eArgs = new TcpServerConnectEventArgs()
                        {
                            Client = client
                        };

                        ClientConnecting?.Invoke(this, eArgs);


                        if (eArgs.Accept)
                        {
                            //Connection Accepted
                            TcpServerConnection newConnection = new TcpServerConnection(this, client)
                            {
                                MessageDelimiter = MessageDelimiter,
                                WsData           = wsData
                            };
                            Trace.WriteLine(Name + ": Connection Accepted: Client = " + newConnection.ClientIPAddress);

                            newConnection.ClientDisconnected += OnClientDisconnected;
                            lock (ActiveConnections) { ActiveConnections.Add(newConnection); }
                            ClientConnected?.Invoke(this, new TcpServerEventArgs()
                            {
                                Client = newConnection
                            });
                        }
                        else
                        {
                            //Connection Refused
                            Trace.WriteLine(Name + ": Connection Rejected.");
                            client.Close();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Trace.WriteLine("[WARNING] " + Name + ": Exception raised from Connection Monitoring Thread!\n" + ex.Message);
                    continue;
                }
            }
        }
        private void Client_ProcessReceivedMessage(TcpServerConnection client, string message, byte[] messageBytes)
        {
            //Parse and Execute Commands
            string[] cmdArg = TcpAppCommon.ParseCommand(message.Trim());

            //Process Command Keyword
            TcpAppCommand cmdHandler = GetCommand(cmdArg[0]);

            if (cmdHandler == null)
            {
                //Error - Unrecognized command.
                client.WriteLineToClient(string.Format("{0} {1} Invalid Command!",
                                                       cmdArg[0], TcpAppCommandStatus.ERR.ToString()));
                return;
            }
            TcpAppInputCommand cmdInput = new TcpAppInputCommand()
            {
                Command = cmdHandler
            };

            cmdInput.Arguments = cmdArg.Skip(1).ToArray(); //Move to TcpAppInputCommand

            //Process Parameters
            cmdHandler.ResetParametersValue();
            int argID = 1; //First Parameter

            foreach (TcpAppParameter item in cmdHandler.Parameters)
            {
                if (argID >= cmdArg.Length)
                {
                    //Argument with no input
                    if (!item.IsOptional)
                    {
                        //Error - Missing required parameter
                        cmdInput.OutputMessage = "Missing required parameter: " + item.Name + "!";
                        WriteResultToClient(client, cmdInput);
                        return;
                    }
                }
                else
                {
                    item.Value = cmdArg[argID]; //Assign parameter value
                }
                argID++;
            }

            //Execute Commands
            try
            {
                cmdInput.Command.ExecuteCallback(cmdInput);
            }
            catch (Exception ex)
            {
                //Catch and report all execution error
                cmdInput.OutputMessage = "Exception Raised! " + ex.Message;
                cmdInput.Status        = TcpAppCommandStatus.ERR; //Force status to error, make sure no surprise.
            }
            finally
            {
                WriteResultToClient(client, cmdInput); //Send result back to client.
            }
        }
Пример #12
0
        private void Client_ProcessReceivedMessage(TcpServerConnection client, string message, byte[] messageBytes)
        {
            //Parse and Execute Commands
            string[] cmdArg = TcpAppCommon.ParseCommand(message.Trim());
            try
            {
                //Register Client Connection
                TcpAppServerConnection ptrClient = AppClients.FirstOrDefault(x => x.Connection == client);
                if (ptrClient == null)
                {
                    //Reconstruct device which had already signed out
                    ptrClient = AddClientToAppClientsList(client);
                }
                Debug.WriteLine("AppServer[" + ptrClient.Name + "]-RX: " + message);

                TcpAppInputCommand inputCommand = TcpAppCommon.CreateInputCommand(Commands, cmdArg);
                if (inputCommand != null)
                {
                    inputCommand.AppClient = ptrClient;
                }
                else//Command keyword not exist
                {
                    //Check if command keyword is alias name
                    ITcpAppServerPlugin plugin = _Plugins.FirstOrDefault(x => string.Compare(x.Alias, cmdArg[0], true) == 0);
                    if (plugin != null)
                    {
                        //Execute plugin command
                        inputCommand           = plugin.GetPluginCommand(cmdArg.Skip(1).ToArray());
                        inputCommand.AppClient = ptrClient;
                        BeforeExecutePluginCommand?.Invoke(this, new TcpAppServerExEventArgs(ptrClient)
                        {
                            Plugin = plugin
                        });
                    }
                    else
                    {
                        //Error - Unrecognized command.
                        inputCommand = new TcpAppInputCommand()
                        {
                            Status        = TcpAppCommandStatus.ERR,
                            OutputMessage = "Invalid Command " + cmdArg[0]
                        };
                        WriteResultToClient(ptrClient, inputCommand);
                        return;
                    }
                }

                //Verify Client had signed in.
                if (!inputCommand.AppClient.SignedIn && !inputCommand.Command.IsSystemCommand)
                {
                    throw new Exception("Client not signed in! Execute SignIn first.");
                }

                if (inputCommand.Command.UseMessageQueue && !inputCommand.Command.IsSystemCommand)
                {
                    //Single thread execution, post message to message queue.
                    lock (CommandQueue)
                    {
                        inputCommand.ID = inputCommand.GetHashCode();
                        if (ptrClient.NextQueuedCommand == null)
                        {
                            ptrClient.NextQueuedCommand = inputCommand;                                      //Set pointer to next queued command.
                        }
                        //Add Command to Queue
                        CommandQueue.Add(inputCommand);
                        CommandQueueWaitSignal?.Set();
                        inputCommand.OutputMessage = inputCommand.ID.ToString();
                        inputCommand.Status        = TcpAppCommandStatus.QUEUED;
                    }
                }
                else if (inputCommand.Command.IsSystemCommand)
                {
                    inputCommand.ExecuteCallback();
                }
                else
                {
                    //Execute command, wait until return
                    if (ExecutionTimeout == 0)
                    {
                        inputCommand.ExecuteCallback();
                    }
                    //Execute command, terminate on timeout
                    else
                    {
                        ptrClient.ExecuteCommandAsync(inputCommand, ExecutionTimeout);
                    }
                }

                WriteResultToClient(ptrClient, inputCommand); //Send result back to client.
            }
            catch (Exception ex)
            {
                WriteExceptionErrorToClient(client, ex);
            }
        }