-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
97 lines (78 loc) · 2.38 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
import os
import pickle
import shlex
import socket
import subprocess
import sys
import threading
from commun.serverData import serverData
from commun.network import *
import dotenv
def runServer(theme="original"):
dotenv_file = dotenv.find_dotenv()
dotenv.load_dotenv(dotenv_file)
os.environ["SERVER_IP"] = "None"
dotenv.set_key(dotenv_file, "SERVER_IP", os.environ["SERVER_IP"])
TB = 2048 * 2
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server = socket.gethostbyname(socket.gethostname())
port = 56669
try:
s.bind((server, port))
print(f"Started server {server} on port {port}")
except socket.error as e:
str(e)
s.listen()
global SRVDATA
SRVDATA = serverData(theme)
global USERS
USERS = []
def threaded_client(conn, id):
# Connection started
global SRVDATA
global USERS
conn.send(pickle.dumps(id))
conn.send(pickle.dumps(SRVDATA))
# main connection loop
while True:
data = recv_data(conn)
stock = pickle.loads(data)
print(stock)
##print(data)
# print("recieved")
SRVDATA.game = stock
# SRVDATA.game.turnChange()
data = pickle.dumps(SRVDATA)
for user in USERS:
send_data(user[0], data)
print("sent")
# connection ends
USERS[id] == None
conn.close()
print("Connection closed")
dotenv_file = dotenv.find_dotenv()
dotenv.load_dotenv(dotenv_file)
os.environ["SERVER_IP"] = server
dotenv.set_key(dotenv_file, "SERVER_IP", os.environ["SERVER_IP"])
while True:
try:
if len(USERS) <= 2:
conn, addr = s.accept()
print("Connected to:", addr)
# id = int(''.join(str(e) for e in [randint(0,9) for x in range(6)]))
id = len(USERS)
USERS.append([conn, addr, id])
thread = threading.Thread(
group=None,
target=threaded_client,
name=f"Player{id}",
args=(conn, id),
kwargs={},
)
thread.start()
except KeyboardInterrupt:
print("\nClosing server")
s.close()
break
if __name__ == "__main__":
runServer()