Exam Princ Python 2023
Exam Princ Python 2023
voir en bas
le client 2 va attendre son tour dans la liste d’attente car le socket est bloquant
serveur.py
client.py
Question 2 : comparaison entre TCP et UDP
5/23/24, 11:49 PM serverThread.py
~/Downloads/serverThread.py
Quetion 3 : socket with thread
1
2 import socket
3 import threading
4
5 # Define a function to handle incoming client connections
6 def handle_client(client_socket, client_address):
7 print(f"New connection from {client_address}")
8
9 # Receive data from the client
10 data = client_socket.recv(1024)
11 msg = data.decode("utf-8")
12
13 # Send a response back to the client
14 if msg == "ping":
15 response = "pong!"
16 client_socket.send(response.encode())
17
18 # Close the connection
19 client_socket.close()
20
21
22 # Define the server's IP address and port number
23 SERVER_ADDRESS = '127.0.0.1'
24 SERVER_PORT = 12345
25
26 # Create a TCP socket object
27 server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
28
29 # Bind the socket to the server's address and port number
30 server_socket.bind((SERVER_ADDRESS, SERVER_PORT))
31
32 # Set the maximum number of queued connections
33 server_socket.listen(5)
34
35 # Main server loop
36 while True:
37 # Accept a new client connection
38 client_socket, client_address = server_socket.accept()
39
40 # Create a new thread to handle the client connection
41 client_thread = threading.Thread(target=handle_client, args=(client_socket,
client_address))
42 client_thread.start()
43
localhost:56858/b32728eb-8ad4-479b-b663-0c94439b6a62/ 1/1