-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
executable file
·51 lines (41 loc) · 1.23 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
import threading
import socket
import sys
if len(sys.argv) != 3 :
print(f"Usage : {sys.argv[0]} <IP> <Port>")
exit()
IP = sys.argv[1]
PORT = int(sys.argv[2])
connections = []
def clientThreadFunc(conn, addr):
conn.send(b"Welcome to the room!")
while True:
try:
message = conn.recv(2048)
if message:
msg = f"<{addr[0]}> : {message.decode()}"
print(msg)
broadcast(msg.encode(), conn)
except:
exit()
def broadcast(msg, msg_owner):
for client_conn in connections:
if client_conn != msg_owner:
try:
client_conn.send(msg)
except:
client_conn.close()
remove(client_conn)
def remove(conn):
if conn in connections:
connections.remove(conn)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((IP, PORT))
server.listen(100)
print(f"Listening at {IP}:{PORT}")
while True:
conn, addr = server.accept()
connections.append(conn)
print(f"{addr} connected")
client_thread = threading.Thread(target=clientThreadFunc, args=((conn, addr)))
client_thread.start()