- 命令和命令加载器实例
- Command类
-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public class ADD : CommandBase<GameSession, GameRequestInfo>
{
string TAG = "ADD:";
public override void ExecuteCommand(GameSession session, GameRequestInfo requestInfo)
{
Console.WriteLine(TAG+"Hello World");
session.Send(requestInfo.ToString());
}
//这个地方开不开启很重要
public override string Name
{
get
{
return "01";
}
}
} Filter
-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20class TerReceiveFilter : TerminatorReceiveFilter<GameRequestInfo>
{
string TAG = "TerReceiveFilter:";
public TerReceiveFilter()
: base(Encoding.Default.GetBytes("##")) //传入固定的请求大小
{
}
//只是进行测试并没有进行解析
protected override GameRequestInfo ProcessMatchedRequest(byte[] data, int offset, int length)
{
Console.WriteLine(TAG + "ProcessMatchedRequest");
///使用一个变量之前必须给它分配相应的内存空间
GameRequestInfo info = new GameRequestInfo();
//如果自己的过滤器重写了Name,那么Name的优先级大于command类的名字
//所以在给Key赋值的时候需要使用Name进行赋值,而不是使用command类的名字
//进行赋值。
info.Key = "01";
return info;
}
} Server
-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19class GameServer : AppServer<GameSession, GameRequestInfo>
{
string TAG = "GameServer:";
public GameServer()
: base(new DefaultReceiveFilterFactory<TerReceiveFilter, GameRequestInfo>())
{
//使用命令之后不需要注册这两个事件
//NewSessionConnected += GameServer_NewSessionConnected;
//NewRequestReceived += GameServer_NewRequestReceived;
}
private void GameServer_NewRequestReceived(GameSession session, GameRequestInfo requestInfo)
{
Console.WriteLine(requestInfo.ToString());
}
private void GameServer_NewSessionConnected(GameSession session)
{
Console.WriteLine(TAG + "GameServer_NewSessionConnected");
}
}
命令过滤器
CommandFilter
1
2
3
4
5
6
7
8
9
10
11
12class GameCommandFilter:CommandFilterAttribute
{
public override void OnCommandExecuted(CommandExecutingContext commandContext)
{
commandContext.Session.Items["StartTime"] = DateTime.Now;
}
public override void OnCommandExecuting(CommandExecutingContext commandContext)
{
var session = commandContext.Session;
session.Logger.InfoFormat("A command '{0}' took {1} seconds!", commandContext.CurrentCommand.Name, DateTime.Now.ToString());
}
}
* Command
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//为此命令应用命令过滤器
[GameCommandFilter]
public class ADD : CommandBase<GameSession, GameRequestInfo>
{
string TAG = "ADD:";
public override void ExecuteCommand(GameSession session, GameRequestInfo requestInfo)
{
Console.WriteLine(TAG+"Hello World");
session.Send(requestInfo.ToString());
}
//这个地方开不开启很重要
public override string Name
{
get
{
return "01";
}
}
}