-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
44 lines (31 loc) · 1.02 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
import socket
import threading
clients = []
def broadcast_msg(msg, conn):
for c in clients:
if c is not conn:
try:
c.send(msg.encode('utf-8'))
except:
c.close()
if c in clients:
clients.remove(c)
with socket.socket() as socket:
address, port = 'localhost', 9999
socket.bind((address, port))
print(f'bound ({address}, {port})')
print('accepting connection')
socket.listen()
while True:
conn, client_address = socket.accept()
clients.append(conn)
def handle_client_connection(conn, addr):
with conn:
while True:
data = conn.recv(1024)
if not data:
break
msg = f'> {addr}: {data.decode("utf-8")}'
print(msg)
broadcast_msg(msg, conn)
threading.Thread(target=handle_client_connection, args=(conn, client_address)).start()