-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.py
163 lines (138 loc) · 5.28 KB
/
Server.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
import socket
import struct
from collections import deque
from threading import Thread, RLock
from RemoteSocket import DATA_FORMAT, DEFAULT_PORT
from TicTacToe import TicTacToe
MAX_CONNECTIONS = 100
PORT = DEFAULT_PORT
HOST = '0.0.0.0'
N = 3
concurrent_print_lock = RLock()
def concurrent_print(*args, **kargs):
global concurrent_print_lock
with concurrent_print_lock:
print(*args, **kargs)
class ConnectionHandler(Thread):
def __init__(self, identifier, server, conn, addr):
Thread.__init__(self)
self.identifier = identifier
self.conn = conn
self.addr = addr
self.server = server
self._closed = False
self.opponent = None
self.game = None
self.player_symbol = None
def __str__(self):
return "%d (%s:%d)" % (self.identifier, *self.addr)
def read_bytes(self, n):
l = 0
data = b''
while not self._closed and l < n:
part = self.conn.recv(n-l)
if not part:
continue
l += len(part)
data += part
return data
def start_game(self, player_symbol, opponent, game):
self.game = game
self.player_symbol = player_symbol
self.opponent = opponent
self.conn.send(struct.pack(DATA_FORMAT, b's', 0 if player_symbol == 'o' else 1, 0, 0))
def send_move(self, data):
self.conn.send(struct.pack(DATA_FORMAT, b'm', *data))
def end_game(self):
self.game = None
self.opponent = None
def run(self):
try:
while not self._closed:
data = self.read_bytes(struct.calcsize(DATA_FORMAT))
parts = struct.unpack(DATA_FORMAT, data)
cmd, data = parts[0], parts[1:]
if cmd == b's':
self.server.game_request(self)
elif cmd == b'm' and self.opponent and self.game.current_player == self.player_symbol:
concurrent_print("Player %s move %s" % (self, data))
match_ended = self.game.on_select(data, debug=False)
self.opponent.send_move(data)
if match_ended:
concurrent_print("Mach %s %s ended %s" % (self, self.opponent, match_ended[0]))
self.opponent.end_game()
self.end_game()
except Exception as e:
concurrent_print("Closing connection %s" % e)
self.close()
def in_game(self):
return (not self._closed) and (self.game is not None) and (self.opponent is not None)
def close(self):
self._closed = True
if self.conn:
self.conn.close()
if self.in_game():
self.opponent.end_game()
self.opponent.conn.send(struct.pack(DATA_FORMAT, b'e', 0, 0, 0))
if self.server:
self.server.disconnect(self)
class Queue:
def __init__(self):
self.elements = set()
self.queue = deque()
self.lock = RLock()
def pushpop2(self, e):
with self.lock:
if e in self.elements:
return None, None
self.queue.appendleft(e)
self.elements.add(e)
if len(self.queue) >= 2:
e1, e2 = self.queue.pop(), self.queue.pop()
self.elements.remove(e1)
self.elements.remove(e2)
return e1, e2
return None, None
def remove(self, e):
with self.lock:
try:
self.queue.remove(e)
self.elements.remove(e)
except ValueError: pass
class Server:
def __init__(self, host=HOST, port=PORT, max_connections=MAX_CONNECTIONS):
self.port = port
self.host = host
self.max_connections = max_connections
self.conn_identifier = 0
self.id_lock = RLock()
self.game_requests = Queue()
def game_request(self, player):
concurrent_print("Received game request from %s" % (player))
player1, player2 = self.game_requests.pushpop2(player)
if player1 and player2 and not player1.in_game() and not player2.in_game():
game = TicTacToe(N)
player2.start_game('o', player1, game)
player1.start_game('x', player2, game)
concurrent_print("Started game between %s and %s" % (player1, player2))
def disconnect(self, player):
self.game_requests.remove(player)
def start(self):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as socket_server:
socket_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
socket_server.bind((self.host, self.port))
socket_server.listen(self.max_connections)
concurrent_print("Started server on %s:%d" % (self.host, self.port))
while True:
conn, addr = socket_server.accept()
with self.id_lock:
self.conn_identifier += 1
identifier = self.conn_identifier
connection_handler = ConnectionHandler(identifier, self, conn, addr)
concurrent_print("Connection from %s" % connection_handler)
connection_handler.start()
def main():
server = Server()
server.start()
if __name__ == '__main__':
main()