forked from murjo06/1D-Chess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
64 lines (57 loc) · 1.42 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
import socket
from _thread import *
import pickle
from game import Game
import config
server = config.SERVER_ADDRESS
port = config.PORT
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((server, port))
except socket.error as e:
str(e)
s.listen(2)
print(f"Waiting for a connection, server started at {server}:{port}")
connected = set()
games = {}
idCount = 0
def threaded_client(conn, p, gameId):
global idCount
conn.send(str.encode(str(p)))
while True:
try:
data = conn.recv(4096).decode()
if gameId in games:
game = games[gameId]
if not data:
break
else:
if data == "reset":
game.resetWent()
elif data != "get":
game.play(p, data)
conn.sendall(pickle.dumps(game))
else:
break
except:
break
print("Lost connection")
try:
del games[gameId]
print("Closing Game", gameId)
except:
pass
idCount -= 1
conn.close()
while True:
conn, addr = s.accept()
print("Connected to: ", addr)
idCount += 1
p = 0
gameId = (idCount - 1)//2
if idCount % 2 == 1:
games[gameId] = Game(gameId)
else:
games[gameId].ready = True
p = 1
start_new_thread(threaded_client, (conn, p, gameId))