-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIPC_Server.py
More file actions
62 lines (49 loc) · 1.67 KB
/
IPC_Server.py
File metadata and controls
62 lines (49 loc) · 1.67 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
import socket
import threading
clients = {}
lock = threading.Lock()
def handle_client(client_socket, client_address):
try:
name = client_socket.recv(1024).decode("utf-8")
with lock:
clients[client_socket] = name
print(f"New client connected: {client_address} as {name}")
broadcast(f"{name} has joined the chat.", client_socket)
while True:
message = client_socket.recv(1024).decode("utf-8")
if message:
print(f"{name}: {message}")
broadcast(f"{name}: {message}", client_socket)
else:
break
except:
pass
finally:
remove_client(client_socket)
def broadcast(message, sender_socket):
with lock:
for client in clients:
if client != sender_socket:
try:
client.sendall(message.encode("utf-8"))
except:
remove_client(client)
def remove_client(client_socket):
with lock:
name = clients.get(client_socket, "Unknown")
print(f"{name} disconnected.")
broadcast(f"{name} has left the chat.", client_socket)
if client_socket in clients:
del clients[client_socket]
client_socket.close()
def start_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("localhost", 8888))
server_socket.listen()
print("Group Chat Server is running...")
while True:
client_socket, client_address = server_socket.accept()
threading.Thread(
target=handle_client, args=(client_socket, client_address)
).start()
start_server()