自定义AppServer

时间:2021-11-27 01:42:34

自定义AppServer

TelnetSever.cs

     public class TelnetServer : AppServer<TelnetSession>
{
protected override bool Setup(IRootConfig rootConfig, IServerConfig config)
{
return base.Setup(rootConfig, config);
} protected override void OnStarted()
{
base.OnStarted();
} protected override void OnStopped()
{
base.OnStopped();
}
}

TelnetSession.cs

     public  class TelnetSession:AppSession<TelnetSession,StringRequestInfo>
{
protected override void OnSessionStarted()
{
Console.WriteLine(this.SessionID + ":Client connected");
Send("Welcome to SuperSocket Telnet Server");
} protected override void HandleUnknownRequest(SuperSocket.SocketBase.Protocol.StringRequestInfo requestInfo)
{
Send("Unknow request");
} protected override void HandleException(Exception e)
{
this.Send("Application error: {0}", e.Message);
} protected override void OnSessionClosed(CloseReason reason)
{
//add you logics which will be executed after the session is closed
Console.WriteLine(this.SessionID + "Client Closed");
base.OnSessionClosed(reason);
}
}

Add.cs

     public class Add : CommandBase<TelnetSession, StringRequestInfo>
{
public override void ExecuteCommand(TelnetSession session, StringRequestInfo requestInfo)
{
session.Send(requestInfo.Parameters.Select(p => Convert.ToInt32(p)).Sum().ToString());
}
}

Program.cs

     class Program
{
static void Main(string[] args)
{
Console.WriteLine("Press any key to start the server!"); Console.ReadKey();
Console.WriteLine();
var appServer = new TelnetServer(); var serverConfig = new ServerConfig
{
Port = //set the listening port
}; //Setup the appServer
if (!appServer.Setup(serverConfig))
{
Console.WriteLine("Failed to setup!");
Console.ReadKey();
return;
} Console.WriteLine(); //Try to start the appServer
if (!appServer.Start())
{
Console.WriteLine("Failed to start!");
Console.ReadKey();
return;
} Console.WriteLine("press key 'q' to stop it!"); while (Console.ReadKey().KeyChar != 'q')
{
Console.WriteLine();
continue;
} Console.WriteLine(); //Stop the appServer
appServer.Stop();
}
}