Exemplo n.º 1
4
 public override void ExecuteCommand(AppSession session, StringPackageInfo requestInfo)
 {
     var paramsArray = requestInfo.Body.Split(' ');
     for (var i = 0; i < paramsArray.Length; i++)
     {
         session.Send(paramsArray[i]);
     }
 }
Exemplo n.º 2
0
        static void appServer_NewRequestReceived(AppSession session, StringPackageInfo requestInfo)
        {
            switch (requestInfo.Key.ToUpper())
            {
                case("ECHO"):
                    session.Send(requestInfo.Body);
                    break;

                case ("ADD"):
                    session.Send(requestInfo.Parameters.Select(p => Convert.ToInt32(p)).Sum().ToString());
                    break;

                case ("MULT"):

                    var result = 1;

                    foreach (var factor in requestInfo.Parameters.Select(p => Convert.ToInt32(p)))
                    {
                        result *= factor;
                    }

                    session.Send(result.ToString());
                    break;
            }
        }
Exemplo n.º 3
0
 public override void ExecuteCommand(TestSession session, StringPackageInfo requestInfo)
 {
     //Console.WriteLine("R:" + requestInfo.Body);
     LastSent = requestInfo.Body;
     session.Send(requestInfo.Body);
     Interlocked.Increment(ref m_Sent);
 }
Exemplo n.º 4
0
        public override void ExecuteCommand(BroadcastSession session, StringPackageInfo requestInfo)
        {
            string message = requestInfo.Body;

            session.AppServer.BroadcastMessage(session, message);
            session.Send("101 message broadcasted");
        }
Exemplo n.º 5
0
        public override void ExecuteCommand(RemoteProcessSession session, StringPackageInfo requestInfo)
        {
            Process[] processes;

            string firstParam = requestInfo.GetFirstParam();

            if (string.IsNullOrEmpty(firstParam) || firstParam == "*")
            {
                processes = Process.GetProcesses();
            }
            else
            {
                processes = Process.GetProcesses().Where(p =>
                                                         p.ProcessName.IndexOf(firstParam, StringComparison.OrdinalIgnoreCase) >= 0).ToArray();
            }

            StringBuilder sb = new StringBuilder();

            foreach (var p in processes)
            {
                sb.AppendLine(string.Format("{0}\t{1}", p.ProcessName, p.Id));
            }

            sb.AppendLine();

            session.Send(sb.ToString());
        }
Exemplo n.º 6
0
        /// <summary>
        /// 通过Socket发送日志
        /// </summary>
        /// <param name="level">日志级别</param>
        /// <param name="beginMark">Stocket信息头</param>
        /// <param name="endMark">Socket信息尾</param>
        /// <param name="logRequest">日志请求</param>
        private static void SendMessage(LogLevel level, string beginMark, string endMark, LogRequest logRequest)
        {
            var pack = new StringPackageInfo(level.ToString(), logRequest.ToJson(), null);
            var msg  = $"{beginMark}{pack.ToJson()}{endMark}";

            client.Send(Encoding.UTF8.GetBytes(msg));
        }
Exemplo n.º 7
0
        static void appServer_NewRequestReceived(AppSession session, StringPackageInfo requestInfo)
        {
            switch (requestInfo.Key.ToUpper())
            {
            case ("ECHO"):
                session.Send(requestInfo.Body);
                break;

            case ("ADD"):
                session.Send(requestInfo.Parameters.Select(p => Convert.ToInt32(p)).Sum().ToString());
                break;

            case ("MULT"):

                var result = 1;

                foreach (var factor in requestInfo.Parameters.Select(p => Convert.ToInt32(p)))
                {
                    result *= factor;
                }

                session.Send(result.ToString());
                break;
            }
        }
Exemplo n.º 8
0
 public override void ExecuteCommand(YourSession session, StringPackageInfo requestInfo)
 {
     foreach (var p in requestInfo.Parameters)
     {
         session.Send(p);
     }
 }
Exemplo n.º 9
0
        public override void ExecuteCommand(StringClient session, StringPackageInfo commandInfo)
        {
            log4j.Debug("ResponseAdd: " + commandInfo.Body);

            // after received data, pass the data to EventHandler
            Data.ResponseAdd responseAdd = Newtonsoft.Json.JsonConvert.DeserializeObject <Data.ResponseAdd>(commandInfo.Body);
            session.PushToResponseAddHandler(responseAdd);
        }
Exemplo n.º 10
0
 public override void ExecuteCommand(TestSession session, StringPackageInfo requestInfo)
 {
     foreach (var p in requestInfo.Parameters)
     {
         Console.WriteLine("S: " + p);
         session.Send(p);
     }
 }
Exemplo n.º 11
0
 /// <summary>
 /// 当读取到数据,触发一个事件,方便外部接收数据
 /// </summary>
 /// <param name="stringPackageInfo"></param>
 public void OnReceived(StringPackageInfo stringPackageInfo)
 {
     Console.WriteLine(stringPackageInfo.Body);
     if (newReceived != null)
     {
         newReceived(stringPackageInfo.Body, new EventArgs());
     }
 }
Exemplo n.º 12
0
        public override void ExecuteCommand(TestSession session, StringPackageInfo requestInfo)
        {
            if (!string.IsNullOrEmpty(requestInfo.Body))
            {
                session.Send(requestInfo.Body);
            }

            session.Close(CloseReason.ServerClosing);
        }
Exemplo n.º 13
0
 public void ProcessPackage(StringPackageInfo package)
 {
     switch (package.Key)
     {
     case "Comm1000":
         CommandProcesser.Comm1000Process(package.Body);
         break;
     }
 }
Exemplo n.º 14
0
        public override void ExecuteCommand(AppSession session, StringPackageInfo requestInfo)
        {
            var paramsArray = requestInfo.Body.Split(' ');

            for (var i = 0; i < paramsArray.Length; i++)
            {
                session.Send(paramsArray[i]);
            }
        }
Exemplo n.º 15
0
        public override void ExecuteCommand(TestSession session, StringPackageInfo requestInfo)
        {
            string[] source = GetStringSource();

            Parallel.For(0, source.Length, (i) =>
            {
                session.Send(source[i]);
            });
        }
Exemplo n.º 16
0
        static async Task Main(string[] args)
        {
            Encoding Utf8Encoding = new UTF8Encoding();

            var pipelineFilter = new CommandLinePipelineFilter
            {
                Decoder = new DefaultStringPackageDecoder()
            };
            IEasyClient <StringPackageInfo> client = new EasyClient <StringPackageInfo>(pipelineFilter);

            StringPackageInfo package = null;

            client.PackageHandler += async(s, p) =>
            {
                package = p;
                if (string.IsNullOrWhiteSpace(p.Key))
                {
                    Console.WriteLine("unexpected result ---------");
                }
                else
                {
                    Console.WriteLine(p.Key);
                }
                await Task.CompletedTask;
            };

            var connected = await client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 8899));

            Console.WriteLine(connected);

            client.StartReceive();

            byte[] bytes1 = Utf8Encoding.GetBytes(new char[] { (char)0x00, (char)0x00, (char)0x01, (char)0x61 });
            byte[] bytes2 = Utf8Encoding.GetBytes(new char[] { (char)0x00, (char)0x00, (char)0x01, (char)0x61, (char)0x62 });
            byte[] bytes3 = Utf8Encoding.GetBytes(new char[] { (char)0x00, (char)0x00, (char)0x01, (char)0x61 });
            byte[] bytes4 = Utf8Encoding.GetBytes(new char[] { (char)0x00, (char)0x00, (char)0x01, (char)0x61 });

            await client.SendAsync(bytes1); //expected result: a, true result: a

            await Task.Delay(1000);

            await client.SendAsync(bytes2); //expected result: a, true result: a

            await Task.Delay(1000);

            await client.SendAsync(bytes3); //expected result: a, true result: null

            await Task.Delay(1000);

            await client.SendAsync(bytes4); //expected result: a, tree result: null

            await Task.Delay(1000);

            await client.CloseAsync();
        }
Exemplo n.º 17
0
        public async Task TestCommandLine(Type hostConfiguratorType)
        {
            var hostConfigurator = CreateObject <IHostConfigurator>(hostConfiguratorType);

            using (var server = CreateSocketServerBuilder <StringPackageInfo, CommandLinePipelineFilter>(hostConfigurator)
                                .UseCommand((options) =>
            {
                options.AddCommand <SORT>();
            }).BuildAsServer())
            {
                Assert.Equal("TestServer", server.Name);

                Assert.True(await server.StartAsync());
                OutputHelper.WriteLine("Server started.");

                var pipelineFilter = new CommandLinePipelineFilter
                {
                    Decoder = new DefaultStringPackageDecoder()
                };

                var options = new ChannelOptions
                {
                    Logger = DefaultLoggerFactory.CreateLogger(nameof(TestCommandLine))
                };
                var client = hostConfigurator.ConfigureEasyClient(pipelineFilter, options);

                StringPackageInfo package = null;

                client.PackageHandler += async(s, p) =>
                {
                    package = p;
                    await Task.CompletedTask;
                };

                var connected = await client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, hostConfigurator.Listener.Port));

                Assert.True(connected);

                client.StartReceive();

                await client.SendAsync(Utf8Encoding.GetBytes("SORT 10 7 3 8 6 43 23\r\n"));

                await Task.Delay(1000);

                Assert.NotNull(package);

                Assert.Equal("SORT", package.Key);
                Assert.Equal("3 6 7 8 10 23 43", package.Body);

                await client.CloseAsync();

                await server.StopAsync();
            }
        }
Exemplo n.º 18
0
        public override void ExecuteCommand(AppSession session, StringPackageInfo requestInfo)
        {
            var result = 1;

            foreach (var factor in requestInfo.Parameters.Select(p => Convert.ToInt32(p)))
            {
                result *= factor;
            }

            session.Send(result.ToString());
        }
Exemplo n.º 19
0
        private void Request(StringPackageInfo obj)
        {
            string str = obj.Key;

            if (str.Contains("\r\n"))
            {
                str = str.Substring(0, str.Length - 2);
            }
            byte[] bs = str.StrToHexByte();
            buff = bs;
            countdownEvent.Signal();
        }
Exemplo n.º 20
0
    protected void HandlePackage(IPackageInfo package)
    {
        Debug.Log("HandlePackage........................");
        StringPackageInfo spi = package as StringPackageInfo;

        if (spi != null)
        {
            Debug.Log("Key:" + spi.Key + " body:" + spi.Body);
            switch (spi.Key)
            {
            }
        }
    }
Exemplo n.º 21
0
 public override void ExecuteCommand(StringClient session, StringPackageInfo commandInfo)
 {
     log4j.Debug("ResponseAdd: " + commandInfo.Body);
     try
     {
         // after received data, pass the data to EventHandler
         TcpClientServer.Data.ResponseAdd responseAdd = Newtonsoft.Json.JsonConvert.DeserializeObject <TcpClientServer.Data.ResponseAdd>(commandInfo.Body);
         session.PushToResponseAddHandler(responseAdd);
     }
     catch (Exception ex)
     {
         log4j.Error("", ex);
     }
 }
Exemplo n.º 22
0
        public override void ExecuteCommand(MyAppSession session, StringPackageInfo requestInfo)
        {
            if (requestInfo.Parameters == null || requestInfo.Parameters.Length != 2)
            {
                return;
            }

            var username = requestInfo.Parameters[0];
            var password = requestInfo.Parameters[1];

            if ("kerry".Equals(username) && "123456".Equals(password))
            {
                session.IsLoggedIn = true;
            }
        }
Exemplo n.º 23
0
        public override void ExecuteCommand(RemoteProcessSession session, StringPackageInfo requestInfo)
        {
            int processId;

            string processKey = requestInfo.Parameters.FirstOrDefault();

            if (string.IsNullOrEmpty(processKey))
            {
                session.Send("No parameter!");
                return;
            }

            if (int.TryParse(processKey, out processId))
            {
                Process process = Process.GetProcessById(processId);
                if (process != null)
                {
                    process.Kill();
                    session.Send("The specific process has been killed!");
                    return;
                }
                else
                {
                    session.Send("The specific process does not exist!");
                }
            }
            else
            {
                List <Process> processes = Process.GetProcesses().Where(p =>
                                                                        p.ProcessName.Equals(processKey, StringComparison.OrdinalIgnoreCase)).ToList();

                processes.ForEach(p => p.Kill());

                if (processes.Count <= 0)
                {
                    session.Send("The specific process does not exist!");
                }
                else if (processes.Count == 1)
                {
                    session.Send("The specific process has been killed!");
                }
                else
                {
                    session.Send(string.Format("The {0} specific process has been killed!", processes.Count));
                }
            }
        }
Exemplo n.º 24
0
        private void MessageReceived(StringPackageInfo spi)
        {
            Dispatcher.Invoke(delegate
            {
                switch (spi.Key)
                {
                case "LOGIN":
                    dckLogin.Visibility = Visibility.Collapsed;
                    dckChat.Visibility  = Visibility.Visible;
                    UpdateText(spi.Body);
                    break;

                case "LOGINERR":
                case "CHATERR":
                case "CHAT":
                    UpdateText(spi.Body);
                    break;

                default:
                    UpdateText(string.Format("{0} {1}", spi.Key, spi.Body));
                    break;
                }
            });
        }
Exemplo n.º 25
0
 public override void ExecuteCommand(TestSession session, StringPackageInfo requestInfo)
 {
     session.Send(AppDomain.CurrentDomain.FriendlyName + "," + AppDomain.CurrentDomain.BaseDirectory);
 }
Exemplo n.º 26
0
 public override void ExecuteCommand(TestSession session, StringPackageInfo requestInfo)
 {
     session.Send("RESU " + (Convert.ToInt32(requestInfo[0]) + Convert.ToInt32(requestInfo[1])).ToString());
 }
Exemplo n.º 27
0
 public override void ExecuteCommand(AppSession session, StringPackageInfo requestInfo)
 {
     session.Send(requestInfo.Parameters.Select(p => Convert.ToInt32(p)).Sum().ToString());
 }
Exemplo n.º 28
0
 public override void ExecuteCommand(AppSession session, StringPackageInfo requestInfo)
 {
     session.Close();
 }
Exemplo n.º 29
0
        public async Task TestCommandLine(Type hostConfiguratorType)
        {
            var hostConfigurator = CreateObject <IHostConfigurator>(hostConfiguratorType);

            using (var server = CreateSocketServerBuilder <StringPackageInfo, CommandLinePipelineFilter>(hostConfigurator)
                                .UseCommand((options) =>
            {
                options.AddCommand <SORT>();
            }).BuildAsServer())
            {
                Assert.Equal("TestServer", server.Name);

                Assert.True(await server.StartAsync());
                OutputHelper.WriteLine("Server started.");

                IEasyClient <StringPackageInfo> client;

                var services = new ServiceCollection();
                services.AddLogging();
                services.Configure <ILoggingBuilder>((loggingBuilder) =>
                {
                    loggingBuilder.AddConsole();
                });

                var sp = services.BuildServiceProvider();

                var loggerFactory = sp.GetService <ILoggerFactory>();
                var logger        = loggerFactory.CreateLogger("Client");

                var pipelineFilter = new CommandLinePipelineFilter
                {
                    Decoder = new DefaultStringPackageDecoder()
                };

                if (hostConfigurator.IsSecure)
                {
                    client = (new SecureEasyClient <StringPackageInfo>(pipelineFilter, logger)).AsClient();
                }
                else
                {
                    client = new EasyClient <StringPackageInfo>(pipelineFilter, logger).AsClient();
                }

                StringPackageInfo package = null;

                client.PackageHandler += (s, p) =>
                {
                    package = p;
                };

                var connected = await client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, hostConfigurator.Listener.Port));

                Assert.True(connected);

                client.StartReceive();

                await client.SendAsync(Utf8Encoding.GetBytes("SORT 10 7 3 8 6 43 23\r\n"));

                await Task.Delay(1000);

                Assert.NotNull(package);

                Assert.Equal("SORT", package.Key);
                Assert.Equal("3 6 7 8 10 23 43", package.Body);

                await client.CloseAsync();

                await server.StopAsync();
            }
        }
Exemplo n.º 30
0
 public override void ExecuteCommand(TestSession session, StringPackageInfo requestInfo)
 {
     session.Send(string.Format(ReplyFormat, requestInfo.Body));
 }
Exemplo n.º 31
0
 public override void ExecuteCommand(AppSession session, StringPackageInfo requestInfo)
 {
     ((MyAppServerA)session.AppServer).DespatchMessage(requestInfo[0], requestInfo[1]);
 }
Exemplo n.º 32
0
 void AppServer_NewRequestReceived(AppSession session, StringPackageInfo requestInfo)
 {
     session.Send(requestInfo.Body);
 }
Exemplo n.º 33
0
 void AppServer_NewRequestReceived(AppSession session, StringPackageInfo requestInfo)
 {
     session.Send(requestInfo.Body);
 }
Exemplo n.º 34
0
 public override void ExecuteCommand(AppSession session, StringPackageInfo requestInfo)
 {
     session.Send(requestInfo.Body);
 }
Exemplo n.º 35
0
 public override void ExecuteCommand(AppSession session, StringPackageInfo requestInfo)
 {
     session.Send(requestInfo.Body);
     Console.WriteLine("S:" + requestInfo.Body);
 }