Implement socket commands

Most of business logics should be placed in in commands which will be executed automatically by SuperSocket engine according found CommandInfo's key.

For example, if SuperSocket engine find a CommandInfo with a key "ECHO"

"ECHO I love you",

the command whose name is "ECHO" will be executed.

Echo command defined like below:

public class ECHO : StringCommandBase<EchoSession>
    {
        #region CommandBase<EchoSession> Members

        public override void ExecuteCommand(EchoSession session, StringCommandInfo commandInfo)
        {
            session.SendResponse(commandInfo.Data);
        }

        #endregion
    }

The method ExecuteCommand will be executed automatically, if SuperSocket engine find a StringCommandInfo with a key "ECHO".

If you have defined your own command info type in your protocol, you should create your command base on CommandBase<SessionType, CommandInfoType>:

 

 

public class ECHO : CommandBase<EchoSession, MyCommandInfo>
    {
        #region CommandBase<EchoSession> Members

        public override void ExecuteCommand(EchoSession session, MyCommandInfo commandInfo)
        {
            session.SendResponse(commandInfo.Data);
        }

        #endregion
    }

 

In some cases, your command info's key must be a hex string or other strings which are not able to be a class name.

We also have a solution to fix it. You can override command's name attribute to match command name with command info's key:

 

public class ECHO : CommandBase<EchoSession, MyCommandInfo>
    {
        public override string Name
        {
            get { return "0A"; }
        }

        #region CommandBase<EchoSession> Members

        public override void ExecuteCommand(EchoSession session, MyCommandInfo commandInfo)
        {
            session.SendResponse(commandInfo.Data);
        }

        #endregion
    }

 

In ExecuteCommand method, you can use session to send message/data to client, and you also can access AppServer's attributes and methods by session.AppServer, so you can use them to implement your business logics of this command.

public override void ExecuteCommand(EchoSession session, MyCommandInfo commandInfo)
        {
            var appServer = session.AppServer;
            //Your business logics
            //Send data to client
            session.SendResponse(commandInfo.Data);
        }

Last edited Mar 19, 2011 at 4:11 AM by kerryjiang, version 7

Comments

No comments yet.