效果:禁止未被授权的连接执行某些命令,这里使用验证登陆为例。
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>
{
}