-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnection.py
209 lines (165 loc) · 5.81 KB
/
connection.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
import utils
import socket
import threading
import pickle
import time
class ErrorDisconnectedFromServer(Exception):
pass
class ErrorReceivingMessage(Exception):
pass
class ErrorSendingMessage(Exception):
pass
class ErrorMessageNotFromServer(Exception):
pass
class ErrorConnectingToServer(Exception):
pass
__HEADER_SIZE__ = 4
__HEADER_AMOUNT__ = 4
class Client:
def __init__(self, ip, port, on_receive=lambda x: None, uid=None):
self.ip = ip
self.port = port
self.uid = (
(utils.generate_random_uid(
str(self.ip) + '$@lt' + str(self.port) + str(time.time())
)
if uid is None else uid))
self.connected = False
self.connection = None
self.on_receive = on_receive
self.timeLast = time.time()
def _dict_wrapper(self, data, type_='data'):
return {
'uid': self.uid,
'time': time.time(),
'data': data,
'type': type_
}
def _receive_once(self):
try:
received = self.connection.recv(__HEADER_SIZE__)
if received == b'':
return
received = int(received)
mes = None
try:
data = self.connection.recv(received)
mes = pickle.loads(data)
mes = utils.Message(mes)
except Exception as e:
print("Error:", e)
mes = None
if mes is not None:
self.on_receive(mes)
except:
print("Closing...")
raise ErrorDisconnectedFromServer
def _rec_forever(self):
assert self.connected
while True:
self._receive_once()
def connect(self):
assert not self.connected
self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.connection.connect((str(self.ip), int(self.port)))
self.connected = True
except:
self.connected = False
self.connection = None
raise ErrorConnectingToServer
def send(self, data, type_='data'):
assert self.connected
wrapper = self._dict_wrapper(data, type_=type_)
dumped_wrapper = pickle.dumps(wrapper)
try:
length = str(len(dumped_wrapper)).encode().rjust(4, b'0')
self.connection.sendall(length + dumped_wrapper)
except Exception as e:
print(e)
raise ErrorSendingMessage
def start(self):
assert not self.connected
self.connect()
self.rec_thread = threading.Thread(target=self._rec_forever)
self.rec_thread.start()
def stop(self):
assert self.connected
self.connection.close()
self.connected = False
self.connection = None
self.rec_thread.join()
class Server:
def __init__(self, port, on_receive=lambda x, y, z, w: None, _newthread_client=True):
self.port = port
self.ip = ''
self.started = False
self._clients = []
self._clientthreads = []
self.on_receive = on_receive
self._newthread_client = True
def send_single(self, client_or_client_index, data):
client = self.clients[client_or_client_index] if type(client_or_client_index) == int else client_or_client_index
dump = pickle.dumps(data) # data is the dict already
try:
length = str(len(dump)).encode().rjust(4, b'0')
client.sendall(length + dump)
except Exception as e:
print(e)
raise ErrorSendingMessage
def send_all(self, data):
for client in self._clients:
self.send_single(client, data)
def send_all_except(self, data, client):
for client in self._clients:
if not client == client:
self.send_single(client, data)
def _handle_single(self, client):
while True:
try:
numchars = client.recv(__HEADER_AMOUNT__)
if numchars == b'':
continue
numchars = int(numchars)
data = client.recv(numchars)
if not data == b'':
data = pickle.loads(data)
self.on_receive(data, self._clients, self, client)
except ConnectionResetError:
print('Client disconnected:', client)
def remove_client(self, client):
self._clients.remove(client)
def _handle_all(self):
for client in self._clients:
self._handle_single(client)
def _handle_forever(self):
while True:
self._handle_all()
def _accept_once(self):
client, address = self.listener.accept()
self._clients.append(client)
print("Got client: %s" % client)
def _accept_forever(self):
while True:
self._accept_once()
def _accept_newthread_forever(self):
while True:
client, address = self.listener.accept()
self._clients.append(client)
point = len(self._clientthreads)
self._clientthreads.append(threading.Thread(target=self._handle_single, args=(client,)))
self._clientthreads[point].start()
def start(self):
assert not self.started
self.listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.listener.bind((self.ip, self.port))
self.listener.listen(5)
print("Server successfully created on port %s" % self.port)
if not self._newthread_client:
self.acceptThread = threading.Thread(target=self._accept_forever)
self.acceptThread.start()
self.handleThread = threading.Thread(target=self._handle_forever)
self.handleThread.start()
else:
self.acceptThread = threading.Thread(target=self._accept_newthread_forever)
self.acceptThread.start()