-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSession.py
229 lines (189 loc) · 7.27 KB
/
Session.py
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
#####################################################################
# -*- coding: iso-8859-1 -*- #
# #
# Frets on Fire #
# Copyright (C) 2006 Sami Kyöstilä #
# #
# This program is free software; you can redistribute it and/or #
# modify it under the terms of the GNU General Public License #
# as published by the Free Software Foundation; either version 2 #
# of the License, or (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software #
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, #
# MA 02110-1301, USA. #
#####################################################################
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import zip
from builtins import object
import pickle
from io import BytesIO
import Network
import Engine
import Log
import World
import Task
try:
reversed
except:
def reversed(seq):
seq = seq[:]
seq.reverse()
return seq
class Message(object):
def __init__(self, **args):
for key, value in list(args.items()):
setattr(self, key, value)
def __repr__(self):
return "<Message %s %s>" % (str(self.__class__), " ".join(["%s='%s'" % (k, v) for k, v in list(self.__dict__.items())]))
class MessageBroker(object):
def __init__(self):
self.messageHandlers = []
def addMessageHandler(self, handler):
if handler not in self.messageHandlers:
self.messageHandlers.append(handler)
def removeMessageHandler(self, handler):
if handler in self.messageHandlers:
self.messageHandlers.remove(handler)
def signalMessage(self, sender, message):
#if not Log.quiet and len(str(message)) < 80:
# Log.debug("From %s: %s" % (sender, message))
# print self.messageHandlers
for handler in reversed(self.messageHandlers):
try:
handler.handleMessage(sender, message)
except Exception as e:
import traceback
traceback.print_exc()
def signalSessionOpened(self, session):
for handler in self.messageHandlers:
handler.handleSessionOpened(session)
def signalSessionClosed(self, session):
for handler in self.messageHandlers:
handler.handleSessionClosed(session)
class MessageHandler(object):
def handleMessage(self, sender, message):
""" This thing is called in turn for all messagehandlers
so a the getattr will fail for most of them, it usually works for the 1st one though """
f = None
try:
n = "handle" + str(message.__class__).split(".")[-1]
# new syntax of __class__ with py3, we have some '> in the end...
if n[-2] == "'":
n = n[:len(n)-2]
f = getattr(self, n, None)
except AttributeError:
return None
if f:
return f(sender, **message.__dict__)
else:
return None
def handleSessionOpened(self, session):
pass
def handleSessionClosed(self, session):
pass
class Phrasebook(object):
def __init__(self):
self.receivedClasses = {}
self.sentClasses = {}
def serialize(data):
s = BytesIO()
pickle.Pickler(s, protocol = 2).dump(data)
return s.getvalue()
serialize = staticmethod(serialize)
def unserialize(data):
return pickle.loads(data)
unserialize = staticmethod(unserialize)
def decode(self, packet):
data = self.unserialize(packet)
id = data[0]
if id < 0:
self.receivedClasses[-id] = data[1:]
Log.debug("Learned about %s, %d phrases now known." % (data[1], len(self.receivedClasses)))
elif id in self.receivedClasses:
message = self.receivedClasses[id][0]()
if len(data) > 1:
message.__dict__.update(dict(list(zip(self.receivedClasses[id][1], data[1:]))))
return message
else:
Log.warn("Message with unknown class received: %d" % id)
def encode(self, message):
packets = []
if not message.__class__ in self.sentClasses:
id = len(self.sentClasses) + 1
definition = [message.__class__, list(message.__dict__.keys())]
self.sentClasses[message.__class__] = [id] + definition
packets.append(self.serialize([-id] + definition))
Log.debug("%d phrases taught." % len(self.sentClasses))
else:
id = self.sentClasses[message.__class__][0]
data = [id] + [getattr(message, key) for key in self.sentClasses[message.__class__][2]]
packets.append(self.serialize(data))
return packets
class BaseSession(Network.Connection, Task.Task, MessageHandler):
def __init__(self, engine, broker, sock = None):
Network.Connection.__init__(self, sock)
self.engine = engine
self.broker = broker
self.phrasebook = Phrasebook()
def __str__(self):
return "<Session #%s at %s>" % (self.id, self.addr)
def isPrimary(self):
return self.id == 1
def run(self, ticks):
pass
def stopped(self):
self.close()
def disconnect(self):
return self.engine.disconnect(self)
def sendMessage(self, message):
#print "Sent by %s:%s: %s" % (self.__class__, self.id, message)
#self.sendPacket(message.serialize())
for packet in self.phrasebook.encode(message):
self.sendPacket(packet)
def handleMessage(self, sender, message):
#print "Received by %s:%s: %s" % (self.__class__, self.id, message)
self.broker.signalMessage(sender, message)
def handleRegistration(self):
Log.debug("Connected as session #%d." % self.id)
def isConnected(self):
return self.id is not None
class ServerSession(BaseSession):
def __init__(self, engine, sock):
BaseSession.__init__(self, engine = engine, broker = engine.server.broker, sock = sock)
self.server = engine.server
self.world = self.server.world
def handlePacket(self, packet):
message = self.phrasebook.decode(packet)
if message:
self.handleMessage(self.id, message)
def handleRegistration(self):
self.broker.signalSessionOpened(self)
def handleClose(self):
self.broker.signalSessionClosed(self)
BaseSession.handleClose(self)
class ConnectionLost(Message): pass
class ClientSession(BaseSession):
def __init__(self, engine):
BaseSession.__init__(self, engine = engine, broker = MessageBroker())
self.world = World.WorldClient(engine, session = self)
self.broker.addMessageHandler(self.world)
self.closed = False
def handleClose(self):
if not self.closed:
self.closed = True
self.broker.signalMessage(0, ConnectionLost())
def handlePacket(self, packet):
message = self.phrasebook.decode(packet)
if message:
self.handleMessage(0, message)
def run(self, ticks):
Network.communicate()