标签:
TelnetSession.cs
1 public class TelnetSession:AppSession<TelnetSession> 2 { 3 protected override void OnSessionStarted() 4 { 5 Send("Welcome to SuperSocket Telnet Server"); 6 } 7 8 protected override void HandleUnknownRequest(SuperSocket.SocketBase.Protocol.StringRequestInfo requestInfo) 9 { 10 Send("Unknow request"); 11 } 12 13 protected override void HandleException(Exception e) 14 { 15 this.Send("Application error: {0}", e.Message); 16 } 17 18 protected override void OnSessionClosed(CloseReason reason) 19 { 20 //add you logics which will be executed after the session is closed 21 base.OnSessionClosed(reason); 22 } 23 }
Echo.cs
1 public class Echo : CommandBase<TelnetSession, StringRequestInfo> 2 { 3 public override void ExecuteCommand(TelnetSession session, StringRequestInfo requestInfo) 4 { 5 session.Send(requestInfo.Body); 6 } 7 }
在这个command代码中,你可以看到类ECHO的父类是CommandBase<AppSession, StringRequestInfo>, 它有一个泛型参数AppSession。 是的,它是默认的AppSession类。 如果你在你的系统中使用你自己建立的AppSession类,那么你必须将你自己定义的AppSession类传进去,否则你的服务器无法发现这个Command:
Add.cs
1 public class Add : CommandBase<TelnetSession, StringRequestInfo> 2 { 3 public override void ExecuteCommand(TelnetSession session, StringRequestInfo requestInfo) 4 { 5 session.Send(requestInfo.Parameters.Select(p => Convert.ToInt32(p)).Sum().ToString()); 6 } 7 }
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<TelnetSession>(); 11 var serverConfig = new ServerConfig 12 { 13 Port = 8000 14 }; 15 16 //Setup the appServer 17 if (!appServer.Setup(serverConfig)) 18 { 19 Console.WriteLine("Failed to setup!"); 20 Console.ReadKey(); 21 return; 22 } 23 Console.WriteLine(); 24 //Try to start the appServer 25 if (!appServer.Start()) 26 { 27 Console.WriteLine("Failed to start!"); 28 Console.ReadKey(); 29 return; 30 } 31 32 Console.WriteLine("The server started successfully, press key ‘q‘ to stop it!"); 33 34 while (Console.ReadKey().KeyChar != ‘q‘) 35 { 36 Console.WriteLine(); 37 continue; 38 } 39 40 Console.WriteLine(); 41 appServer.Stop(); 42 43 Console.WriteLine("The server was stopped!"); 44 } 45 }
标签:
原文地址:http://www.cnblogs.com/caoyc/p/4707516.html