-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexercise3.py
More file actions
27 lines (18 loc) · 715 Bytes
/
Copy pathexercise3.py
File metadata and controls
27 lines (18 loc) · 715 Bytes
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
# 🧠 Question: How can a server handle multiple connections using threading?
import socket
import threading
import time
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("0.0.0.0", 9999))
server_socket.listen(2)
def handle_client(connection, address):
thread_id = threading.current_thread().ident
print(f"Thread {thread_id} handling {address}")
time.sleep(5)
print(f"Thread {thread_id} done with {address}")
connection.close()
while True:
connection, address = server_socket.accept()
print(f"Accepted connection from {address}")
thread = threading.Thread(target= handle_client, args=(connection, address))
thread.start()