-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnet_server.py
More file actions
111 lines (88 loc) · 3.02 KB
/
net_server.py
File metadata and controls
111 lines (88 loc) · 3.02 KB
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
import socket
import threading
import json
HOST = "127.0.0.1"
PORT = 5000
# Guarda as ligações por role
clients = {
"assaulter": None,
"van": None,
}
clients_lock = threading.Lock()
def broadcast_to_other(role, raw_line: bytes):
"""Reenvia a linha EXACTAMENTE como chegou para o outro jogador."""
other_role = "van" if role == "assaulter" else "assaulter"
with clients_lock:
other_conn = clients.get(other_role)
if other_conn is not None:
try:
# já vem com \\n no fim porque vem de makefile.readline()
other_conn.sendall(raw_line)
except OSError:
pass
def handle_client(conn, addr):
print(f"[SERVER] new connection {addr}")
role = None
# Ler em modo texto para o HELLO (plaintext)
f = conn.makefile("rb")
try:
# 1) HELLO em claro
hello_line = f.readline()
if not hello_line:
print(f"[SERVER] {addr} closed before hello")
conn.close()
return
try:
hello = json.loads(hello_line.decode("utf-8").strip())
except json.JSONDecodeError as e:
print(f"[SERVER] invalid hello from {addr}:", e, "line:", hello_line)
conn.close()
return
if hello.get("type") != "hello":
print(f"[SERVER] first msg from {addr} is not hello:", hello)
conn.close()
return
role = hello.get("role")
if role not in ("assaulter", "van"):
print(f"[SERVER] invalid role from {addr}:", role)
conn.close()
return
with clients_lock:
clients[role] = conn
print(f"[SERVER] {addr} registered as {role}")
# 2) HELLO_ACK em claro
ack = {"type": "hello_ack", "role": role}
ack_line = (json.dumps(ack) + "\n").encode("utf-8")
conn.sendall(ack_line)
# 3) A partir daqui o servidor é CEGO:
# só lê linhas e faz forward bruto para o outro role.
for raw_line in f:
if not raw_line:
break
# poderias só logar tamanho / tipo
# print(f"[SERVER] {role} -> {len(raw_line)} bytes ciphertext")
broadcast_to_other(role, raw_line)
except OSError as e:
print(f"[SERVER] Error {addr}: {e}")
finally:
print(f"[SERVER] Client {addr} ({role}) disconnected")
if role is not None:
with clients_lock:
if clients.get(role) is conn:
clients[role] = None
try:
conn.close()
except OSError:
pass
def main():
print(f"[SERVER] listening on {HOST}:{PORT}.")
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen()
while True:
conn, addr = s.accept()
t = threading.Thread(target=handle_client, args=(conn, addr), daemon=True)
t.start()
if __name__ == "__main__":
main()