-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
53 lines (39 loc) · 1.17 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
import threading
import socket
PORT = 5050
SERVER = 'localhost' #local ip of private machine running
ADDR = (SERVER, PORT)
FORMAT = "utf-8"
DISCONNECT_MESSAGE = "Disconnected from server."
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
clients = set()
clients_lock = threading.Lock()
def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr} Connected!")
try:
connected = True
while connected:
msg = conn.recv(1024).decode(FORMAT)
if not msg:
break
if msg == DISCONNECT_MESSAGE:
connected = False
print(f"[{addr}] {msg}")
with clients_lock:
for c in clients:
c.sendall(f"[{addr}] {msg}".encode(FORMAT))
finally:
with clients_lock:
clients.remove(conn)
conn.close()
def start():
print("[SERVER STARTED]")
server.listen()
while True:
conn, addr = server.accept()
with clients_lock:
clients.add(conn)
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
start()