SuperSocket服务器架设(五):使用命令过滤器

效果:禁止未被授权的连接执行某些命令,这里使用验证登陆为例。

 

1.      在MySession中添加bool类型的变量isLogin:

 

2.      创建类MyCommandFilterAttribute,继承自CommandFilterAttribute,并重写方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperSocket.Common;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Protocol;

namespace SuperSocketApp1
{
    public class MyCommandFilterAttribute : CommandFilterAttribute
    {
        /// <summary>
        /// 命令监视器-执行命令前调用
        /// </summary>
        /// <param name="commandContext"></param>
        public override void OnCommandExecuting(CommandExecutingContext commandContext)
        {
            //throw new NotImplementedException();

            MySession session = commandContext.Session as MySession;

            //判断是否已登录
            if (session != null && !session.isLogin)
            {
                //判断当前命令是否为LOGIN
                if (!commandContext.RequestInfo.Key.Equals("LOGIN"))
                {
                    //取消执行当前命令
                    commandContext.Cancel = true;
                }
            }
        }

        /// <summary>
        /// 命令监视器-执行命令后调用
        /// </summary>
        /// <param name="commandContext"></param>
        public override void OnCommandExecuted(CommandExecutingContext commandContext)
        {
            //throw new NotImplementedException();
        }
    }
}

3.      创建类LOGIN,模仿登陆过程:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;

namespace SuperSocketApp1.Command
{
    class LOGIN : CommandBase<MySession, StringRequestInfo>
    {
        public override void ExecuteCommand(MySession session, StringRequestInfo requestInfo)
        {
            session.isLogin = true;
            session.Send("登陆成功。");
        }
    }
}

4.      给要应用此过滤器的类添加属性

    [MyCommandFilterAttribute]
    public class SEND : CommandBase<MySession, StringRequestInfo>
    {
        public override void ExecuteCommand(MySession session, StringRequestInfo requestInfo)
        {
           //此处省略N行代码
        }
    }

5.      若要给所有的命令类应用此过滤器,则给MyServer添加属性

    [MyCommandFilter]
    public class MyServer : AppServer<MySession>
    {
        
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值