分离Command

要点:

1.请求类必须继承CommandBase
2.请求类类名为请求对象中的Key值,大小写可以不区分
3.类必须用public修饰,否则无法识别该请求,提示为无效请求
4.不能再调用NewRequestReceived事件

代码实现:

Program.cs

 1     class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             Console.WriteLine("Press any key to start the server!");
 6 
 7             Console.ReadKey();
 8             Console.WriteLine();
 9 
10             var appServer = new AppServer();
11 
12             //Setup with config model, which provides more options
13             var serverConfig = new ServerConfig
14             {
15                 Port = 8000, //set the listening port
16                 //Other configuration options
17                 //Mode = SocketMode.Udp,
18                 //MaxConnectionNumber = 100,
19                 //...
20             };
21 
22             //Setup the appServer
23             if (!appServer.Setup(serverConfig))
24             {
25                 Console.WriteLine("Failed to setup!");
26                 Console.ReadKey();
27                 return;
28             }
29 
30             appServer.NewSessionConnected += new SessionHandler<AppSession>(appServer_NewSessionConnected);
31 
32             Console.WriteLine();
33 
34             //Try to start the appServer
35             if (!appServer.Start())
36             {
37                 Console.WriteLine("Failed to start!");
38                 Console.ReadKey();
39                 return;
40             }
41 
42             Console.WriteLine("The server started successfully, press key 'q' to stop it!");
43 
44             while (Console.ReadKey().KeyChar != 'q')
45             {
46                 Console.WriteLine();
47                 continue;
48             }
49 
50             Console.WriteLine();
51             //Stop the appServer
52             appServer.Stop();
53 
54             Console.WriteLine("The server was stopped!");
55         }
56 
57         static void appServer_NewSessionConnected(AppSession session)
58         {
59             session.Send("Welcome to SuperSocket Telnet Server");
60         }
61     }
View Code

Echo.cs

1     public class ADD : CommandBase<AppSession, StringRequestInfo>
2     {
3         public override void ExecuteCommand(AppSession session, StringRequestInfo requestInfo)
4         {
5             session.Send(requestInfo.Parameters.Select(p => Convert.ToInt32(p)).Sum().ToString());
6         }
7     }
View Code
原文地址:https://www.cnblogs.com/caoyc/p/4707411.html