SuperSocket entry (2)-exploring AppServer, AppSession, Conmmand, App. config, and supersocketsession

Source: Internet
Author: User

SuperSocket entry (2)-exploring AppServer, AppSession, Conmmand, App. config, and supersocketsession
In the previous article, we have learned how to process client requests in SuperSocket. At the same time, we may find a problem. If our server contains a lot of complicated business logic, such switch/case code will be very long and ugly, and does not follow the object-oriented design principle (OOD ). In this case, SuperSocket provides some command frameworks that allow us to process different requests in multiple independent classes. Next let's take a look at how to use them.1. Custom AppSessionAppSession indicates a logical connection to the client. Connection-based operations should be placed in this class. You can use an instance of this type to send data to the client, receive the data sent by the client, or close the connection. Usage: create a custom class MySession, inherit the AppSession class, and override the AppSession class (Note: An AppSession object corresponds to a connection)

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; using SuperSocket. common; using SuperSocket. socketBase; using SuperSocket. socketBase. protocol; /*************************************** * ************************** Author: * CLR version: 4.0.30319.42000 * created after dawn before dusk * Time: 00:02:17*2017 * Description: Custom connection class MySession, inherited AppSession, and passed in to AppSession ** modification history: ******** **************************************** * *****************/Namespace SuperSocketDemo. session {// <summary> /// custom connection class MySession, inherit from AppSession, and pass it to AppSession /// </summary> public class MySession: appSession <MySession >{/// <summary> // new connection // </summary> protected override void OnSessionStarted () {// output the Console of the Client IP address. writeLine (this. localEndPoint. address. toString (); this. send ("Hello User, Welco Me to SuperSocket Telnet Server! ");} /// <Summary> /// Unknown Command /// </summary> /// <param name = "requestInfo"> </param> protected override void HandleUnknownRequest (StringRequestInfo requestInfo) {this. send ("unknow ");} /// <summary> /// catch an exception and output /// </summary> /// <param name = "e"> </param> protected override void HandleException (exception e) {this. send ("error: {0}", e. message );} /// <summary> /// Connection closed /// </summary> /// <param name = "reason"> </param> protected override void OnSessionClosed (CloseReason reason) {base. onSessionClosed (reason );}}}
MySession class 2. Custom AppServerAppServer represents the server instance that listens to the client connection and carries the TCP connection. Ideally, we can use the AppServer instance to obtain any client connection you want. Server-level operations and logic should be defined in this class. Usage: create a custom class MyServer, inherit the AppServer class, and override the AppServer class.
Using SuperSocket. socketBase; using SuperSocket. socketBase. config; using SuperSocketDemo. session; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; /*************************************** * ************************** Author: * CLR version: 4.0.30319.42000 * created at: 00:15:45*2017 * Description: Custom server class MyServer, inherited AppServer, and input the custom connection class MySession ** modification history: **************************************** * **************************/namespace SuperSocketDemo. server {// <summary> /// the custom Server class MyServer inherits the AppServer and passes in the Custom connection class MySession /// </summary> public class MyServer: appServer <MySession> {protected override void OnStartup () {base. onStartup (); // Console. writeLine ("server startup ");} /// <summary> /// output new connection information /// </summary> /// <param name = "session"> </param> protected override void OnNewSessionConnected (mySession session) {base. onNewSessionConnected (session); // output the Client IP address Console. write ("\ r \ n" + session. localEndPoint. address. toString () + ": Connection ");} /// <summary> /// output the disconnection information /// </summary> /// <param name = "session"> </param> /// <param name = "reason"> </param> protected override void OnSessionClosed (MySession session, closeReason reason) {base. onSessionClosed (session, reason); Console. write ("\ r \ n" + session. localEndPoint. address. toString () + ": disconnected");} protected override void OnStopped () {base. onStopped (); Console. writeLine ("Service stopped ");}}}
MyServer Class 3 Use CommandThe Command in SuperSocket allows us to expand, and the usage is extremely simple. You only need to inherit a CommandBase <AppSession, StringRequestInfo> class (Note: if a custom Session is used, you need to modify it here, for example, add: CommandBase <MySession, StringRequestInfo> under the Add class) class), and override this class ExecuteCommand method. Now let's handle the example in the previous article. First, cancel the appServer. NewRequestReceived event processing in the Telnet example. In this way, we can write a large number of commands to make our Socket more flexible. For example, we can define a class named "Hello" to process requests whose Key is "Hello:
Public class Hello: CommandBase <MySession, StringRequestInfo >{//< summary> /// customize the command execution method, note that the input variable session type is MySession // </summary> /// <param name = "session"> session </param> /// <param name = "requestInfo "> request data information </param> public override void ExecuteCommand (MySession session, stringRequestInfo requestInfo) {session. send (string. format ("Hello {0 }:{ 1} {2}", session. config. ip, session. config. port, requestInfo. body ));}}
Hello class

Define a class named "ADD" to process requests whose Key is "ADD:

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

Define a class named "MULT" to process requests whose Key is "MULT:

public class MULT : CommandBase<MySession, StringRequestInfo>{    public override void ExecuteCommand(MySession session, StringRequestInfo requestInfo)    {        var result = 1;        foreach (var factor in requestInfo.Parameters.Select(p => Convert.ToInt32(p)))        {            result *= factor;        }        session.Send(result.ToString());    }}
The Mult class defines a class named "Echo" to process requests whose Key is "Echo:
public class Echo: CommandBase<MySession, StringRequestInfo>    {        public override void ExecuteCommand(MySession session, StringRequestInfo requestInfo)        {            session.Send(requestInfo.Body);        }    }
Echo class

At the same time, we need to remove the registration of the request processing method because it and the command cannot be supported at the same time. Just comment out the following code.

// AppServer. NewRequestReceived + = new RequestHandler <MySession, StringRequestInfo> (appServer_NewRequestReceived );

4. Configure App. config to start SuperSocket using BootStrap

SuperSocket configuration section SuperSocket uses the configuration technology that comes with. NET. SuperSocket has a special configuration Section. You can use the configuration to enable SuperSocket flexible configuration options.

After the configuration is complete, you also need to modify the program class. Comment out the port information and method defined in program, and only keep the code for starting and stopping the service. Introduce using SuperSocket. SocketEngine; start with BootStrap

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; using SuperSocket. socketBase; using SuperSocket. socketBase. protocol; using SuperSocket. socketEngine; using SuperSocketDemo. server; /*************************************** * ************************** Author: * CLR version: 4.0.30319.42000 * created at: 00:02:17*2017 * Description: Service start and stop entry ** modification history: 2017- 01-19 adjust the custom mysession and myserver ******************************* * **********************************/namespace SuperSocketDemo {class Program {// <summary> // SuperSocket service starts or stops /// </summary> // <param name = "args"> </param> static void Main (string [] args) {Console. writeLine ("press any key to start the SuperSocket service! "); Console. ReadKey (); Console. WriteLine (); var bootstrap = BootstrapFactory. CreateBootstrap (); if (! Bootstrap. Initialize () {Console. WriteLine ("initialization failed! "); Console. readKey (); return;} // modify the appserver to myserver // var appServer = new AppServer (); // var appServer = new MyServer (); // register the event // appServer. newSessionConnected + = new SessionHandler <AppSession> (appServer_NewSessionConnected); // appServer. newRequestReceived + = new RequestHandler <AppSession, StringRequestInfo> (appServer_NewRequestReceived); // set the port number // int port = 2017; // start the application service port // if (! AppServer. Setup (port) // listening port 2017 at startup // {// Console. WriteLine ("service port startup failed! "); // Console. ReadKey (); // return; //} // Console. WriteLine (); // try to start the application service // if (! AppServer. Start () // {// Console. WriteLine ("service startup failed! "); // Console. ReadKey (); // return; //} var result = bootstrap. Start (); Console. WriteLine (" the service is starting: {0 }! ", Result); if (result = StartResult. Failed) {Console. WriteLine (" service startup Failed! "); Console. ReadKey (); return;} Console. WriteLine (" the service has been started successfully. Please press 'e' to stop the service! "); While (Console. ReadKey (). KeyChar! = 'E') {Console. writeLine (); continue;} // stop the service // appServer. stop (); bootstrap. stop (); Console. writeLine ("Service stopped! "); Console. readKey ();} /// <summary> /// send the welcome message to the client in the event processing code // </summary> /// <param name = "session"> </param> // static void appServer_NewSessionConnected (AppSession session) // {// session. send ("Welcome to SuperSocket Telnet Server! "); /// // <Summary> // process client requests /// </summary> /// <param name = "session"> session </param> // /<param name = "requestInfo"> Request Information </param> // static void appServer_NewRequestReceived (AppSession session, stringRequestInfo 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 ;//}//}}}
Program class

Finally, let's take a look at the modified program running result:

Check the effect of disconnecting the debugging tool. The server displays that the client is disconnected.

Note:

A) The access permissions of MyServer, custom commands, and MySession must be set to public B. The parent class of MyServer is AppServer <MySession> c) the parent class of MySession is AppSession <MySession> d) HELLO, the parent class is CommandBase <MySession, StringRequestInfo>. The input values of the ExecueteCommand method are MySession and StringRequestInfo e) note that the AppSession, AppServer, and custom commands in multiple servers should not be mistaken for debugging Common Errors:

Summary:

Through the custom Session and Server, we can implement our own AppSession and AppServer, allowing you to easily expand SuperSocket according to your business needs, you can bind session connection and disconnection events, the Start and Stop events of the server instance. You can also read your custom configuration information in the Setup method of AppServer. All in all, these functions allow you to easily create a socket server you need.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.