C # Socket server framework SuperSocket tutorial (b)

I. realize your AppServer and AppSession

What is AppSession?

Representative AppSession and a logical connection to the client, based on the operation should be scheduled to be connected in the class. You can transmit data to the client instance of the class, the data sent by a client or close the connection.

What is AppServer?

AppServer represents listen for client connections, the server instance carrying TCP connection. Ideally, we can get anything you want AppServer examples of client connections, server-level operations and logic should be defined in this class.

Create your AppSession

  1. The method of the base class you can override

    public class TelnetSession : AppSession<TelnetSession>
    {
        protected override void OnSessionStarted()
        {
            this.Send("Welcome to SuperSocket Telnet Server");
        }
    
        protected override void HandleUnknownRequest(StringRequestInfo requestInfo)
        {
            this.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
            base.OnSessionClosed(reason);
        }
    }
    

    In the above code, when a new connection, the server immediately sends a welcome message to the client. This code is also rewritten to AppSession Other methods to achieve their business logic.

  2. You can add new properties to the Session class based on your business needs, let me create AppSession class will be used in a game server:

    public class PlayerSession :AppSession<PlayerSession>
    {
        public int GameHallId { get; internal set; }
    
        public int RoomId { get; internal set; }
    }
    
  3. And the relationship between the Command

    In the previous document, we talked about the Command, and now we have to re-look at this knowledge:

    public class ECHO : CommandBase<AppSession, StringRequestInfo>
    {
        public override void ExecuteCommand(AppSession session, StringRequestInfo requestInfo)
        {
            session.Send(requestInfo.Body);
        }
    }
    

    In this command code, you can see the ECHO parent class is CommandBase <AppSession, StringRequestInfo>, which has a generic parameter AppSession. Yes, it is the default AppSession class. If you build your own class using AppSession in your system, then you have your own definition of AppSession pass in class, or you can not find the server Command:

    public class ECHO : CommandBase<PlayerSession, StringRequestInfo>
    {
        public override void ExecuteCommand(PlayerSession session, StringRequestInfo requestInfo)
        {
            session.Send(requestInfo.Body);
        }
    }
    

Create your AppServer type

  1. If you want to use your AppSession as a session, you must modify your AppServer to use it

    public class TelnetServer : AppServer<TelnetSession>
    {
    
    }
    

    Now TelnetSession will be used in TelnetServer session.

  2. There are also many ways you can rewrite protected

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

advantage

Implement your own AppSession and AppServer allows you to easily based on your business needs expand SuperSocket, you can bind session connection and disconnection event, start and stop the server instance event. You can also read your custom configuration information in Setup method AppServer's. Taken together, these features allow you to easily create a socket server you need possible.

II. Start by configuring SuperSocket

Why start by configuring?

  1. Avoid hard-coding
  2. SuperSocket provides many useful configuration options
  3. You can take advantage of tools provided SuperSocket

How to configure using Bootstrap start SuperSocket

  • SuperSocket configuration section SuperSocket built using .NET configuration technology, SuperSocket have a special configuration Section:

    <configSections>
        <section name="superSocket"
             type="SuperSocket.SocketEngine.Configuration.SocketServiceConfig, SuperSocket.SocketEngine" />
    </configSections>
    
  • Configuration Server instance

    <superSocket>
        <servers>
          <server name="TelnetServer"
              serverType="SuperSocket.QuickStart.TelnetServer_StartByConfig.TelnetServer, SuperSocket.QuickStart.TelnetServer_StartByConfig"
              ip="Any" port="2020">
          </server>
        </servers>
    </superSocket>
    

    Now, I am here to explain server node configuration:

    name: 实例名称
    serverType: 实例运行的AppServer类型
    ip: 侦听ip
    port: 侦听端口
    

    We will in the next one document in a more complete introduction to configuration.

  • Use BootStrap start SuperSocket

    static void Main(string[] args)
    {
        Console.WriteLine("Press any key to start the server!");
    
        Console.ReadKey();
        Console.WriteLine();
    
        var bootstrap = BootstrapFactory.CreateBootstrap();
    
        if (!bootstrap.Initialize())
        {
            Console.WriteLine("Failed to initialize!");
            Console.ReadKey();
            return;
        }
    
        var result = bootstrap.Start();
    
        Console.WriteLine("Start result: {0}!", result);
    
        if (result == StartResult.Failed)
        {
            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
        bootstrap.Stop();
    
        Console.WriteLine("The server was stopped!");
        Console.ReadKey();
    }
    
  • Some configuration examples

  • Server types node:

        <superSocket>
            <servers>
              <server name="TelnetServer"
                  serverTypeName="TelnetServer"
                  ip="Any" port="2020">
              </server>
            </servers>
            <serverTypes>
                <add name="TelnetServer" type="SuperSocket.QuickStart.TelnetServer_StartByConfig.TelnetServer, SuperSocket.QuickStart.TelnetServer_StartByConfig"/>
            </serverTypes>
        </superSocket>
    
  • Multiple server instances:

        <superSocket>
            <servers>
              <server name="TelnetServerA"
                  serverTypeName="TelnetServer"
                  ip="Any" port="2020">
              </server>
              <server name="TelnetServerB"
                  serverTypeName="TelnetServer"
                  ip="Any" port="2021">
              </server>
            </servers>
            <serverTypes>
                <add name="TelnetServer" type="SuperSocket.QuickStart.TelnetServer_StartByConfig.TelnetServer, SuperSocket.QuickStart.TelnetServer_StartByConfig"/>
            </serverTypes>
          </superSocket>
    

SuperSocket.SocketService.exe, SuperSocket provide operational container

  • Directly SuperSocket.SocketService.exe

  • Be sure to make your server required for all assemblies are in the same directory and SuperSocket.SocketService.exe

  • SuperSocket your configuration file placed in SuperSocket.SocketService.exe.config
  • Direct run "SuperSocket.SocketService.exe", you define the server will run

  • SuperSocket.SocketService.exe install as a Windows Service

By adding the command line parameter "-i" run SuperSocket.SocketService.exe, you can install it as a Windows service:

SuperSocket.SocketService.exe -i

The name is defined in the Windows services configuration file, you can modify it to suit your needs:

<appSettings>
    <add key="ServiceName" value="SuperSocketService" />
</appSettings>

You can also uninstall the service via the parameter "-u":

SuperSocket.SocketService.exe -u

Three .SuperSocket basic configuration 

A configuration example

<?xml version="1.0"?>
<configuration>
    <configSections>
        <section name="superSocket"
                 type="SuperSocket.SocketEngine.Configuration.SocketServiceConfig, SuperSocket.SocketEngine" />
    </configSections>
    <appSettings>
        <add key="ServiceName" value="SupperSocketService" />
    </appSettings>
    <superSocket>
        <servers>
            <server name="TelnetServerA"
                    serverTypeName="TelnetServer"
                    ip="Any"
                    port="2020">
            </server>
            <server name="TelnetServerB"
                    serverTypeName="TelnetServer"
                    ip="Any"
                    port="2021">
            </server>
        </servers>
        <serverTypes>
            <add name="TelnetServer"
                 type="SuperSocket.QuickStart.TelnetServer_StartByConfig.TelnetServer, SuperSocket.QuickStart.TelnetServer_StartByConfig"/>
        </serverTypes>
    </superSocket>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
    </startup>
</configuration>

Root configuration

Node Configuration "superSocket" root SuperSocket configuration, which defines the global parameters SuperSocket required. Let's look at the root of all configuration properties:

  • maxWorkingThreads: maximum number of thread pool worker thread;
  • minWorkingThreads: Minimum number of thread pool worker thread;
  • maxCompletionPortThreads: maximum number of completion port thread pool thread;
  • minCompletionPortThreads: the completion of a minimum number of port thread pool threads;
  • disablePerformanceDataCollector: whether to disable the collection of performance data;
  • performanceDataCollectInterval: Performance data collection frequency (in seconds, default: 60);
  • isolation: SuperSocket server instance isolation level
    • None - no isolation
    • AppDomain - application domain level of isolation, multiple server instances running in separate application domain
    • Process - the process level isolation, multiple server instances run in separate processes
  • logFactory: The default name logFactory of all the available log factories defined in the child node "logFactories" in, we will introduce it in the following documents;
  • defaultCulture: Default thread culture entire program, available only in the .Net 4.5;

Server instance configuration

In the root node, the node has a child called "servers", you can define one or more server nodes to represent the server instance. Examples of these servers may be the same type AppServer, or may be of different types.

All properties Server node as follows:

  • name: the name of the server instance;
  • serverType: type the full name of the server instance;
  • serverTypeName: the selected type in the name serverTypes server node configured to define nodes serverTypes server types are available, we will do in detail later;
  • ip: ip address of the server is listening. You can set a specific address, can also be set to the following values ​​Any - all IPv4 addresses IPv6Any - all IPv6 addresses
  • port: server listening port;
  • listenBacklog: monitor size of the queue;
  • mode: Socket server running mode, Tcp (default) or Udp;
  • disabled: server instance is disabled;
  • startupOrder: server startup sequence instance, bootstrap in the order of this value to start multiple server instances;
  • sendTimeOut: timeout transmission data;
  • sendingQueueSize: maximum transmit queue length, the default value is 5;
  • maxConnectionNumber: maximum allowable number of connection;
  • receiveBufferSize: receive buffer size;
  • sendBufferSize: sending buffer size;
  • syncSend: Synchronous transmission mode is enabled, the default value: false;
  • logCommand: whether the recording command execution;
  • logBasicSessionActivity: whether to record the basic activities of the session, such as connection and disconnection;
  • clearIdleSession: true or false, if the timing empty idle session, the default value is false;
  • clearIdleSessionInterval: Empty idle session time interval, the default value is 120 seconds;
  • idleSessionTimeOut: session idle timeout period; when the session idle time exceeds this value, when configured to simultaneously clearIdleSession true, the session will be closed; the default value is 300 seconds;
  • . Security: Empty, transport layer encryption protocol Tls, Ssl3 Socket server employed, the default value is empty;
  • maxRequestLength: maximum permissible length of the request, the default of 1024;
  • textEncoding: default text encoding, default is ASCII;
  • defaultCulture: This server instance default thread culture, only available in .Net 4.5 and void at the isolation level is 'None';
  • disableSessionSnapshot: whether to disable snapshot session, the default value is false.
  • sessionSnapshotInterval: the snapshot interval session, the default value is 5 seconds;
  • keepAliveTime: network connection keep alive interval data transmission in the normal case, the default value is 600 seconds;
  • keepAliveInterval: After the Keep alive failure, Keep alive probe packet transmission interval default value is 60 seconds;
  • This information X509Certificate certificate used to define the nodes of this server instance: certificate

    It is used in two ways:

    • Load certificate from file

        <certificate filePath="localhost.pfx" password="supersocket" />
      
    • Load certificate from the local certificate store

        <certificate storeName="My" storeLocation="LocalMachine" thumbprint="‎f42585bceed2cb049ef4a3c6d0ad572a6699f6f3"/>
      
  • connectionFilter: definition of the name of the connected filter used for example, a plurality of filter medium ',' or ';' separated. Available connectors filter defined in a child node of the root node, would do more described in the following documents;

  • commandLoader: the name of the instance is defined commands used loader, a plurality of filter medium ',' or ';' separated. Loader available commands defined in a child node of the root node, will do more described in the following documents;

  • logFactory: custom logging facility (LogFactory) used by the instance name. Available logs factory (LogFactory) defined in a child node of the root node, we will do more described in the following documents; if you do not set this property, the definition will be used in the plant root log (LogFactory) , if the plant root is also defined log (LogFactory), this example will use the built-in log log4net plant (LogFactory);

  • listeners: This configuration server instance node for supporting a plurality of listening IP / port combinations. This configuration node should contain one or more nodes have about the listener attributes:

    ip: the listening ip;
    port: the listening port;
    backlog: the listening back log size;
    security: the security mode (None/Default/Tls/Ssl/...);
    

    E.g:

    <server name="EchoServer" serverTypeName="EchoService">
      <listeners>
        <add ip="Any" port="2012" />
        <add ip="IPv6Any" port="2012" />
      </listeners>
    </server>
    
  • receiveFilterFactory: receiver name defined filter plant of this example is used;

Server type configuration

Server node type is set in a configuration below the root node. You can add one or more configuration elements have attributes 'name' and 'type' of:

    <serverTypes>
        <add name="TelnetServerType"
             type="SuperSocket.QuickStart.TelnetServer_StartByConfig.TelnetServer, SuperSocket.QuickStart.TelnetServer_StartByConfig"/>
    </serverTypes>

Since the given name of a server type for the "TelnetServerType", you can be a server instance node attribute "serverTypeName" is set to "TelnetServerType", for operating the above types of servers:

    <server name="TelnetServerA"
            serverTypeName="TelnetServerType"
            ip="Any"
            port="2020">
    </server>

Log Factories Configuration

Configuration and server nodes of the same type, one can also define a plurality of L or log facility (LogFatory) and then use server instance. The only difference is that it may be disposed on the root node configuration:

<logFactories>
  <add name="ConsoleLogFactory"
       type="SuperSocket.SocketBase.Logging.ConsoleLogFactory, SuperSocket.SocketBase" />
</logFactories>

In the root node is set LogFactory:

<superSocket logFactory="ConsoleLogFactory">
    ...
    ...
</superSocket>

In the server node is set LogFactory:

<server name="TelnetServerA"
       logFactory="ConsoleLogFactory"
       ip="Any"
       port="2020">
</server>

Configuring IntelliSense tips

SuperSocket provides online XSD (XML Schema Document) to help you easy to configure. You simply add three lines of code in your SuperSocket configuration section:

  <superSocket xmlns="http://schema.supersocket.net/supersocket"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="http://schema.supersocket.net/supersocket http://schema.supersocket.net/v1-6/supersocket.xsd">
    <!---->
  </superSocket>

Then you can get IntelliSense automatically prompts when you update SuperSocket configuration:

SuperSocket Configuration Intellisense

Configuring SuperSocket Windows services

As you probably know, SuperSocket provides a container that can run Windows service in the form of "SuperSocket.SocketService.exe".

You can define this name by configuring Windows services:

<appSettings>
    <add key="ServiceName" value="SuperSocketService" />
</appSettings>

It also supports other configuration properties for Windows services:

ServiceDescription: 此Windows服务的描述
ServicesDependedOn: 此服务依赖的其他服务; 此服务价格会在其依赖的服务启动之后再启动; 多个依赖服务用 ',' 或者 ';' 分割

ps: the above are switched http://www.supersocket.net/ 

Guess you like

Origin blog.csdn.net/a462575515/article/details/93462623