forked from panda3d/panda3d
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetMessenger.py
More file actions
executable file
·94 lines (81 loc) · 2.84 KB
/
NetMessenger.py
File metadata and controls
executable file
·94 lines (81 loc) · 2.84 KB
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
82
83
84
85
86
87
88
89
90
91
92
from direct.directnotify import DirectNotifyGlobal
from direct.distributed.PyDatagram import PyDatagram
from direct.showbase.Messenger import Messenger
from pickle import dumps, loads
# Messages do not need to be in the MESSAGE_TYPES list.
# This is just an optimization. If the message is found
# in this list, it is reduced to an integer index and
# the message string is not sent. Otherwise, the message
# string is sent in the datagram.
MESSAGE_TYPES=(
"avatarOnline",
"avatarOffline",
"create",
"needUberdogCreates",
"transferDo",
)
# This is the reverse look up for the recipient of the
# datagram:
MESSAGE_STRINGS={}
for i in zip(MESSAGE_TYPES, range(1, len(MESSAGE_TYPES)+1)):
MESSAGE_STRINGS[i[0]]=i[1]
class NetMessenger(Messenger):
"""
This works very much like the Messenger class except that messages
are sent over the network and (possibly) handled (accepted) on a
remote machine (server).
"""
notify = DirectNotifyGlobal.directNotify.newCategory('NetMessenger')
def __init__(self, air, channels):
"""
air is the AI Repository.
channels is a list of channel IDs (uint32 values)
"""
assert self.notify.debugCall()
Messenger.__init__(self)
self.air=air
self.channels=channels
for i in self.channels:
self.air.registerForChannel(i)
def clear(self):
assert self.notify.debugCall()
for i in self.channels:
self.air.unRegisterChannel(i)
del self.air
del self.channels
Messenger.clear(self)
def send(self, message, sentArgs=[]):
"""
Send message to All AI and Uber Dog servers.
"""
assert self.notify.debugCall()
datagram = PyDatagram()
# To:
datagram.addUint8(1)
datagram.addChannel(self.channels[0])
# From:
datagram.addChannel(self.air.ourChannel)
#if 1: # We send this just because the air expects it:
# # Add an 'A' for AI
# datagram.addUint8(ord('A'))
messageType=MESSAGE_STRINGS.get(message, 0)
datagram.addUint16(messageType)
if messageType:
datagram.addString(str(dumps(sentArgs)))
else:
datagram.addString(str(dumps((message, sentArgs))))
self.air.send(datagram)
def handle(self, pickleData):
"""
Send pickleData from the net on the local netMessenger.
The internal data in pickleData should have a tuple of
(messageString, sendArgsList).
"""
assert self.notify.debugCall()
messageType=self.air.getMsgType()
if messageType:
message=MESSAGE_TYPES[messageType-1]
sentArgs=loads(pickleData)
else:
(message, sentArgs) = loads(pickleData)
Messenger.send(self, message, sentArgs=sentArgs)