Server-side Programs
1 #-*-coding:utf-8-*-2 #!/usr/bin/python3 """4 5 """6 ImportSocket7 ImportSYS8 ImportThreading9 TenCon =Threading. Condition () oneHOST = Raw_input ("input the server ' s IP adrress:")#symbolic name meaning all available interfaces aPORT = 8888#arbitrary non-privileged Port -data ="' - thes =Socket.socket (socket.af_inet, Socket. Sock_stream) - Print 'Socket created' - s.bind ((HOST, PORT)) -S.listen (10) + Print 'Socket now listening' - + #Function for handling Connections. this'll be used to create threads a defClientthreadin (conn, nick): at GlobalData - #Infinite loop so, function does not terminate and thread does not end. - whileTrue: - #receiving from client - Try: -temp = Conn.recv (1024) in if nottemp: - conn.close () to return + Notifyall (temp) - PrintData the except: *Notifyall (nick +"leaves the room!") $ PrintDataPanax Notoginseng return - the #came out of loop + a defNotifyall (sss): the GlobalData + ifCon.acquire (): -data =SSS $ Con.notifyall () $ con.release () - - defclientthreadout (conn, nick): the GlobalData - whileTrue:Wuyi ifCon.acquire (): the con.wait () - ifData: wu Try: - conn.send (data) about con.release () $ except: - con.release () - return - a + while1: the #wait to accept a connection-blocking call -conn, addr =s.accept () $ Print 'Connected with'+ addr[0] +':'+ STR (addr[1]) theNick = Conn.recv (1024) the #send only takes string the #start new thread takes 1st argument as a function name to being run, second is the tuple of arguments to the function. theNotifyall ('Welcome'+ Nick +'To the room!') - PrintData in PrintStr ((threading.activecount () + 1)/2) +'person (s)!' the conn.send (data) theThreading. Thread (target = clientthreadin, args =(conn, nick)). start () aboutThreading. Thread (target = clientthreadout, args =(conn, nick)). start () the theS.close ()
Client-side Programs
1 #-*-coding:utf-8-*-2 #/usr/bin/python3 4 """5 6 """7 8 ImportSocket9 ImportThreadingTen one aInstring ="' -Outstring ="' -Nick ="' the - defdealout (s): - Globalnick, outstring. - whileTrue: +Outstring =raw_input () -outstring = Nick +': '+outstring + s.send (outstring) a at defDealin (s): - Globalinstring - whileTrue: - Try: -instring = S.recv (1024) - if notinstring: in break - ifoutstring! =instring: to Printinstring + except: - break the * $Nick = Raw_input ("Input your nickname:")Panax NotoginsengIP = raw_input ("input the server ' s IP adrress:") -Sock =Socket.socket (socket.af_inet, Socket. Sock_stream) theSock.connect ((ip, 8888)) + sock.send (nick) a theThin = Threading. Thread (target = dealin, args =(sock,)) + Thin.start () -Thout = Threading. Thread (target = dealout, args =(sock,)) $Thout.start ()
Run results
1 running the program on the server side
2 Client program Run results
Client Run Results
Python chat Room