1- # echo-server.py
2-
31import socket
2+ import threading
3+
4+ class ClientThread (threading .Thread ): #Définition de notre class, celle-ci correspondra à chaque client
5+
6+ def __init__ (self , ip , port , clientsocket ):
7+
8+ threading .Thread .__init__ (self )
9+ self .ip = ip
10+ self .port = port
11+ self .clientsocket = clientsocket
12+ print ("[+] Nouveau thread pour %s %s" % (self .ip , self .port , ))
13+
14+ def run (self ):
15+
16+ print ("Connexion de %s %s" % (self .ip , self .port , ))
17+
18+ r = self .clientsocket .recv (2048 ) # On récupère la date qui nous a été envoyé
19+ r = r .decode ("utf8" ) # On décode la data qui a été encodé juste avant son envoi
20+ print (r )
21+
22+ # Data que nous allons envoyé au client
23+
24+ print ("Que voulez-vous envoyer au client " , self .ip , self .port , " ?" )
25+ data = input (">> " )
26+ data = data .encode ("utf8" ) # On encode la data avant son envoi
27+ self .clientsocket .sendall (data ) # On envoie la date au client correspondant
28+
29+ print ("Client déconnecté..." )
30+
31+ tcpsock = socket .socket (socket .AF_INET , socket .SOCK_STREAM )
32+ tcpsock .setsockopt (socket .SOL_SOCKET , socket .SO_REUSEADDR , 1 )
33+ tcpsock .bind (("127.0.0.1" ,12086 )) # On définit l'adresse ip et le port de notre serveur
434
5- HOST = "127.0.0.1" # Standard loopback interface address (localhost)
6- PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
7-
8- with socket .socket (socket .AF_INET , socket .SOCK_STREAM ) as s :
9- s .bind ((HOST , PORT ))
10- s .listen ()
11- conn , addr = s .accept ()
12- with conn :
13- print (f"Connected by { addr } " )
14- while True :
15- data = conn .recv (1024 )
16- if not data :
17- break
18- conn .sendall (data )
35+ while True : # Cette boucle attends la connextion des clients et les créée selon la class définit plus haut
36+ tcpsock .listen (10 )
37+ print ( "En écoute..." )
38+ (clientsocket , (ip , port )) = tcpsock .accept ()
39+ newthread = ClientThread (ip , port , clientsocket ) # Création d'un thrad réservé au client
40+ newthread .start ()
0 commit comments