-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_py.py
More file actions
69 lines (56 loc) · 2.03 KB
/
Copy pathserver_py.py
File metadata and controls
69 lines (56 loc) · 2.03 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
57
58
59
60
61
62
63
64
65
66
67
68
69
import socket
import threading
# List to keep track of connected clients
clients = []
def handle_client(conn, addr):
"""Handle messages from a connected client"""
print(f"[NEW CONNECTION] {addr} connected.")
while True:
try:
# Receive message from client
msg = conn.recv(1024)
if not msg:
break
# Broadcast the message to all other clients
broadcast(msg, conn)
except:
# Client disconnected or error occurred
break
# Clean up when client disconnects
print(f"[DISCONNECT] {addr} disconnected.")
clients.remove(conn)
conn.close()
def broadcast(message, exclude_conn):
"""Send message to all connected clients except the sender"""
for client in clients:
if client != exclude_conn:
try:
client.send(message)
except:
# Remove client if sending fails
pass
def start_server(host='127.0.0.1', port=12345):
"""Start the chat server"""
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
server.bind((host, port))
server.listen()
print(f"[LISTENING] Server is running on {host}:{port}")
print("[INFO] Waiting for clients to connect...")
while True:
# Accept new client connections
conn, addr = server.accept()
clients.append(conn)
# Start a new thread to handle the client
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.daemon = True # Thread will close when main program closes
thread.start()
except KeyboardInterrupt:
print("\n[SHUTDOWN] Server is shutting down...")
except Exception as e:
print(f"[ERROR] Server error: {e}")
finally:
server.close()
if __name__ == "__main__":
start_server()