基于进程内通讯的python聊天室实现方法
本文实例讲述了基于进程内通讯的python聊天室实现方法。分享给大家供大家参考。具体如下:
#!/usr/bin/envpython #Addedby<ctang@redhat.com> importsys importos frommultiprocessingimportconnection ADDR=('',9997) AUTH_KEY='12345' classServer(object): def__init__(self,username): self.auth_key=AUTH_KEY self.addr=ADDR self.username=username self.listener=connection.Listener(self.addr,authkey=self.auth_key) deflisten(self): whileTrue: conn=self.listener.accept() whileTrue: try: request=conn.recv() response=self.response(request) conn.send(response) exceptEOFError: break conn.close() defreply(self): message=raw_input("%s:"%self.username) returnmessage defoutput_request(self,request): sys.stdout.write('%ssays:%s\n'%request) defresponse(self,request): self.output_request(request) response=(self.username,self.reply()) returnresponse classClient(object): def__init__(self,username): self.auth_key=AUTH_KEY self.addr=ADDR self.username=username self.display_name=self.make_display_name(username) defmake_display_name(self,username): return"%s:"%username defconnect(self): self.conn=connection.Client(self.addr,authkey=self.auth_key) whileTrue: message=raw_input(self.display_name) self.send(message) response=self.conn.recv() self.output_response(response) defsend(self,message): self.conn.send((self.username,message)) defoutput_response(self,response): sys.stdout.write('%ssays:%s\n'%response) defmain(): mode=sys.argv[1] ifmode=='server': username=raw_input("Yournameplease:") server=Server(username) server.listen() elifmode=='client': username=raw_input("Yournameplease:") client=Client(username) client.connect() if__name__=='__main__': main()
希望本文所述对大家的Python程序设计有所帮助。