| 12
 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
 
 | # -*- coding: utf-8 -*-
 
import socket, sys, threading , urllib
page = urllib.urlopen("http://www.monip.org/").read()
host = str(page.split("IP : ")[1].split("<br>")[0])
port = 40520
 
class ThreadClient(threading.Thread):
    def __init__(self, conn):
        threading.Thread.__init__(self)
        self.connexion = conn
 
     def run(self):        nom = self.getName()        
	 msgClient = self.connexion.recv(1024)
	 if msgClient.upper() == "FIN" or msgClient =="":
                break
            message = "%s> %s" % (nom, msgClient)
            print message
            for cle in conn_client:
                if cle != nom:      
                    conn_client[cle].send(message)
        self.connexion.close()      
        del conn_client[nom]        
        print "Client %s déconnecté." % nom
 
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    mySocket.bind((host, port))
except socket.error:
    print "La liaison du socket à l'adresse choisie a échoué."
    sys.exit()
print "Serveur prêt, en attente de requêtes ..."
mySocket.listen(5)
conn_client = {}                
while 1:    
    connexion, adresse = mySocket.accept()
    th = ThreadClient(connexion)
    th.start()
    it = th.getName()        
    conn_client[it] = connexion
    print "Client %s connecté, adresse IP %s, port %s." %\
           (it, adresse[0], adresse[1])
    connexion.send("Vous êtes connecté. Envoyez vos messages.") | 
Partager