-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
56 lines (44 loc) · 1.39 KB
/
server.py
File metadata and controls
56 lines (44 loc) · 1.39 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
# server.py
import socket
import threading
clients = {}
def handle_client(sock, addr):
try:
username = sock.recv(1024).decode().strip()
clients[username] = sock
print(f"[SERVER] {username} {addr} joined the chat")
# Notify others
for user, client in clients.items():
if client != sock:
client.send(f"[SERVER] {username} joined".encode())
while True:
msg = sock.recv(1024)
# Client disconnected
if not msg:
break
msg = msg.decode()
print(f"[RECEIVED] {username}: {msg}")
# Broadcast
for user, client in clients.items():
if client != sock:
client.send(f"{username}: {msg}".encode())
except Exception as e:
print(f"[ERROR] {e}")
finally:
print(f"[SERVER] {username} left the chat")
del clients[username]
sock.close()
# Notify others
for user, client in clients.items():
client.send(f"[SERVER] {username} left".encode())
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("localhost", 12345))
server.listen()
print("[SERVER] Started")
while True:
client_sock, addr = server.accept()
threading.Thread(
target=handle_client,
args=(client_sock, addr),
daemon=True
).start()