This repository has been archived by the owner on Jul 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
executable file
·69 lines (59 loc) · 1.8 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
#!/usr/bin/env python3
import asyncio
from _thread import *
import sys
import socket
import json
import tictactoe
from game import *
import pickle
if __name__ == "__main__":
host = input("Enter host: ")
port = int(input("Enter port: "))
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
server.bind((host, port))
except socket.error as e:
print(e)
server.listen(2)
print("Waiting for connection, {}:{}".format(host, port))
board = [[0]*3 for _ in range(3)]
connected = set()
games: dict[int, Game] = {}
idCount = 0
def threaded_client(conn: socket.socket, p, gameId):
conn.send(str.encode(str(p)))
reply = ""
while True:
try:
data = conn.recv(4096).decode()
if gameId in games:
game = games[gameId]
if not data:
break
else:
if data == "reset":
game.reset()
elif data != "get":
game.play(p, data)
conn.sendall(pickle.dumps(game))
else:
break
except:
break
try:
while True:
conn, addr = server.accept()
print("Connected to:", addr)
idCount += 1
p = 0
gameId = (idCount - 1) // 2
if idCount % 2 == 1:
games[gameId] = Game(gameId)
print("Creating new game")
else:
games[gameId].ready = True
p = 1
start_new_thread(threaded_client, (conn, p, gameId))
except KeyboardInterrupt:
server.close()