-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNetwork.py
237 lines (195 loc) · 6.55 KB
/
Network.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
230
231
232
233
234
235
236
237
#####################################################################
# -*- 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 FakeNetworking import socket, asyncore
import asyncore
import socket
import struct
import time
import io
import Log
PORT = 12345
class ObjectCollection(dict):
def __init__(self):
dict.__init__(self)
self.idCounter = -1
self.objMap = {}
def add(self, object, id = None):
id = id or self.generateId()
self[id] = object
return id
def id(self, object):
try:
return self.objMap[object]
except KeyError:
pass
def __delitem__(self, id):
try:
del self.objMap[self[id]]
del self[id]
except KeyError:
pass
def __setitem__(self, id, object):
self.objMap[object] = id
dict.__setitem__(self, id, object)
def generateId(self):
self.idCounter += 1
return self.idCounter
class Connection(asyncore.dispatcher):
def __init__(self, sock = None):
asyncore.dispatcher.__init__(self, sock = sock)
self.id = None
self.server = None
self._buffer = []
self._sentSizeField = False
self._receivedSizeField = 0
self._packet = io.BytesIO()
if not sock:
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
#def __getattr__(self, name):
# print ">>>", name
# return asyncore.dispatcher.__getattr__(self, name)
def connect(self, host, port = PORT):
assert self.id is None
asyncore.dispatcher.connect(self, (host, port))
# do a blocking connect
n = 0
while not self.connected and n < 600:
communicate()
n += 1
if n > 100:
time.sleep(.1)
def accept(self, id):
assert self.id is None
self.id = id
self._buffer.append(struct.pack("H", self.id))
self.handleRegistration()
def setServer(self, server):
self.server = server
def handleConnect(self):
pass
def handle_connect(self):
return self.handleConnect()
def handle_read(self):
try:
if not self._receivedSizeField:
data = self.recv(2)
if data:
self._receivedSizeField = struct.unpack("H", data)[0]
return
data = self.recv(self._receivedSizeField)
if data:
self._receivedSizeField -= len(data)
self._packet.write(data)
if not self._receivedSizeField:
# The first packet contains the ID
if self.id is None:
self.id = struct.unpack("H", self._packet.getvalue())[0]
self.handleRegistration()
else:
self.handlePacket(self._packet.getvalue())
self._packet.truncate()
self._packet.seek(0)
except socket.error as e:
Log.error("Socket error while receiving: %s" % str(e))
def writable(self):
return len(self._buffer) > 0
def sendPacket(self, packet):
self._buffer.append(packet)
def handlePacket(self, packet):
pass
def close(self):
asyncore.dispatcher.close(self)
self.handle_close()
def handleClose(self):
if self.server:
self.server.handleConnectionClose(self)
self.id = None
def handle_close(self):
return self.handleClose()
def handleRegistration(self):
pass
def handle_write(self):
try:
data = self._buffer[0]
if not self._sentSizeField:
self.send(struct.pack("H", len(data)))
self._sentSizeField = True
if (type(data) == str):
data = str.encode(data)
sent = self.send(data)
data = data[sent:]
if data:
self._buffer[0] = data
else:
self._buffer = self._buffer[1:]
self._sentSizeField = False
except socket.error as e:
Log.error("Socket error while sending: %s" % str(e))
class Server(asyncore.dispatcher):
def __init__(self, port = PORT, localOnly = True):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind((localOnly and "localhost" or "", port))
self.listen(5)
self.clients = {}
self.__idCounter = 0
def handle_accept(self):
sock, addr = self.accept()
self.__idCounter += 1
conn = self.createConnection(sock = sock)
conn.setServer(self)
conn.accept(self.__idCounter)
self.clients[self.__idCounter] = conn
self.handleConnectionOpen(conn)
def createConnection(self, sock):
return Connection(sock = sock)
def handleConnectionOpen(self, connection):
pass
def close(self):
asyncore.dispatcher.close(self)
self.handle_close()
def handleClose(self):
for c in list(self.clients.values()):
c.close()
def handle_close(self):
return self.handleClose()
def handleConnectionClose(self, connection):
if connection.id in self.clients:
del self.clients[connection.id]
def broadcastPacket(self, packet, ignore = [], meToo = True):
for c in list(self.clients.values()):
if not c.id in ignore:
c.sendPacket(packet)
if meToo:
list(self.clients.values())[0].handlePacket(packet)
def sendPacket(self, receiverId, packet):
self.clients[receiverId].sendPacket(packet)
def communicate(cycles = 1):
while cycles:
asyncore.poll(0, asyncore.socket_map)
cycles -= 1
def shutdown():
asyncore.close_all()