-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
50 lines (40 loc) · 1.24 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
import threading
import socket
PORT = 5050
SERVER = "localhost"
# socket.gethostbyname(socket.gethostname()) this will give the local ip address of the machine which is running the code
ADDR = (SERVER,PORT)
FORMAT = "utf-8"
DISCONNECT_MESSAGE = "[!] DISCONNECTED!"
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind(ADDR)
clients = set()
clients_lock = threading.Lock()
def handleClient(conn, addr):
print(f"[+]NEW CONNECTION \n {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=handleClient,args=(conn, addr))
thread.start()
start()