Recently because of the examination of various review by the way to brush TV, feel with the small partners playing more and more unhappy, must have been too busy recently, uh. So want to study the proxy server, download a code, found unexpectedly also involves socket programming, so the network class before the socket Chat room small lesson set out to tidy up ideas.
Code reference: http://www.oschina.net/code/snippet_1387924_25928
Paste the code First:
#Coding:utf-8ImportSocketImportSYSImportThreadingclassServer (object):__data="' #Defining private Variables __con=threading. Condition ()#to create a new lock object __sock=socket.socket (socket.af_inet, socket. SOCK_STREAM)#creating a Socket object def __init__(self,host='localhost', port=6008,max_num=10):#Initialize SocketSelf.__sock. Bind ((HOST, PORT)) self.__sock. Listen (Max_num)#set maximum number of listeners Print 'waiting for access, listening port:', PORTdef __del__(self):#Close SocketSelf.__sock. Close ()def __notifyall(self,text):ifSelf.__con. Acquire ():#If you get a lockSelf.__data=text self.__con. Notifyall () self.__con. Release ()def __clientthreadin(Self,conn,nick):#the process that receives the message whileTrue:Try: Temp= CONN.RECV (1024) if nottemp:conn.close ()returnSelf .__notifyall(temp)PrintSelf.__data except: Self.__notifyall("Server:"+ Nick +"leaves the room!") PrintSelf.__data return def __clientthreadout(Self,conn,nick):#process for sending messages whileTrue:ifSelf.__con. Acquire (): Self.__con. Wait ()ifSelf.__data: Try: Conn.send (self.__data) self.__con. Release ()except: Self.__con. Release ()return defMain (self): whileTrue:conn, addr= self.__sock. Accept ()Print 'Connect, client IP:', addr Nick= CONN.RECV (1024) self.__notifyall('Server:welcome'+ Nick +'To the room!') #Print str ((Threading.activecount () + 1)/2) + ' person (s)! 'Conn.send (self.__data) Threading. Thread (Target= self.__clientthreadin, args =(conn, Nick)). Start () threading. Thread (Target= self.__clientthreadout, args =(conn, Nick)). Start () server=Server () Server.main ()
server.py
#Coding:utf-8ImportSocketImportThreadingclassClient (object):__nick="' __instring="' __outstring="' __sock=Socket.socket (socket.af_inet, socket. SOCK_STREAM)def __init__(self,port=6008,nick="'): Self.__sock. Connect ('localhost', Port)) ifnick!="': Self.__nick=NickElse: Self.__nick= Raw_input ("input your nickname:") self.__sock. Send (self.__nick) def __del__(self): self.__sock. Close ()defMain (self): thin= Threading. Thread (target = self.__dealin). Start () Thout= Threading. Thread (target = self.__dealout). Start ()def __dealout(self): whiletrue:self.__outstring=raw_input () self.__outstring= self.__nick+': '+ Self.__outstringSelf .__sock. Send (self.__outstring) def __dealin(self): whileTrue:Try: Self.__instring= self.__sock. recv (1024) if notSelf.__instring: Break ifSelf.__instring!=self.__outstring: PrintSelf.__instring except: BreakClient=Client () client.main ()
client.py
- The code is divided into two parts:client.py,server.py, client and server, respectively, where clients can run multiple.
- Both the server side and the client use the socket and thread(thread), which is written in an object-oriented way.
- Client.py is relatively simple. The analysis is as follows: first the nickname information is initialized and the corresponding port is monitored. The member function in main declares two threads, one for sending information and one for receiving information. When no information is received, the program stops waiting at socket.recv () . When no message is sent, the program stops at raw_input () and waits for input.
- server.pythe analysis is as follows: first initialize the listening port information, wait for the client to access. If you detect aClientAccess, firstrecv Clientthe nickname information, and to all theClientissue an announcement. Serverfor each of the connectedClientall two processes are processed, sending and receiving respectively. After the Send function obtains the lock, it stops waiting, unlocks the current lock, and switches to the receive function. When no information is received, the receive function issocket.recv ()waiting. After receiving theClientafter the message is sent, call theNotifyall ()function, cancels the current lock, notifies all sending processes, andClientsend a message.
Python Socket Programming App