forked from en/libunity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dispatcher.cs
81 lines (66 loc) · 1.96 KB
/
Dispatcher.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using UnityEngine;
using System.Collections.Generic;
namespace NetProto
{
public class Dispatcher
{
public delegate object MsgHandler(byte[] data);
class Group
{
public MsgHandler handler;
// action注册一次,执行一次,它在handler之后被执行
// action的输入为handler的返回值
public System.Action<object> action;
}
Dictionary<Api.ENetMsgId, Group> msgMap = new Dictionary<Api.ENetMsgId, Group>();
public Dispatcher()
{
}
public void Register(NetHandle handle)
{
foreach(var v in handle.handlerMap)
{
RegisterHandler(v.Key, v.Value);
}
}
public bool RegisterHandler(Api.ENetMsgId id, MsgHandler handler)
{
if (msgMap.ContainsKey(id))
{
Debug.LogError(id + " is already registered");
return false;
}
Group g = new Group();
g.handler = new MsgHandler(handler);
g.action = null;
msgMap.Add(id, g);
return true;
}
public bool RegisterAction(Api.ENetMsgId id, System.Action<object> act)
{
if (!msgMap.ContainsKey(id))
{
Debug.LogError("register handler of " + id + " first");
return false;
}
msgMap[id].action = act;
return true;
}
public bool InvokeHandler(Api.ENetMsgId id, byte[] data)
{
if (!msgMap.ContainsKey(id))
{
Debug.LogError(id + " is not registered");
return false;
}
Group g = msgMap[id];
object ret = g.handler(data);
if (g.action != null)
{
g.action.Invoke(ret);
g.action = null;
}
return true;
}
}
}