44 lines
1.3 KiB
Python
44 lines
1.3 KiB
Python
import socket
|
|
import threading
|
|
|
|
HOST = socket.gethostbyname("localhost")
|
|
PORT = 5053
|
|
ADDR = (HOST, PORT)
|
|
HEADER = 64
|
|
FORMAT = "utf-8"
|
|
|
|
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
server.bind(ADDR)
|
|
|
|
def handleClient(conn, addr):
|
|
client_name = conn.recv(HEADER).decode(FORMAT)
|
|
print(f"[NEW CONNECTION] {client_name} connected.")
|
|
connected = True
|
|
while connected:
|
|
msg_length = conn.recv(HEADER).decode(FORMAT)
|
|
if msg_length:
|
|
msg_length = int(len(msg_length))
|
|
msg = conn.recv(msg_length).decode(FORMAT)
|
|
if msg == "!DISCONNECT":
|
|
connected = False
|
|
print(f"[{client_name}] {msg}")
|
|
conn.send("Msg received".encode(FORMAT))
|
|
|
|
conn.send("Bye bye".encode(FORMAT))
|
|
conn.close()
|
|
print(f"[DISCONNECTED] {client_name} disconnected.")
|
|
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 2}]")
|
|
|
|
|
|
|
|
def start():
|
|
server.listen()
|
|
print(f"[LISTENING] Server is listening on {HOST}")
|
|
while True:
|
|
conn, addr = server.accept()
|
|
thread = threading.Thread(target=handleClient, args=(conn, addr))
|
|
thread.start()
|
|
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
|
|
|
|
print("[STARTING] server is starting...")
|
|
start() |