资源描述:
《Python简单的多客户端聊天室程序源代码》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、本文所示代码将教你如何使用Python标准库中的select.select模块实现筈路复用的命令行下CS模式的聊尺*程序。服务器端代码:#!/usr/bin/envpython〃〃〃Abasic,multiclient'chatserver"usingPython'sselectmodulewithinterrupthandling.Enteringemyinputattheterminolwi11exittheserver.importselectimportsocketimportsysimportsigna
2、ilfromcommunicationimportsend,receiveBUFSIZ二4096classChatServer(object):Simplechatserverusingselectdef_init_(self,port二3490,backlog=5):self,clients=0#Clientmapself,clientmap二{}#Outputsocketlistself,outputs二[]self,server=socket,socket(socket.AF_INET,socket.SOC
3、K_STREAM)self.server.setsockopt(socket.S0L_S0CKET,socket.SO_REUSEADDR,1)self,server,bind((‘',port))print'Listeningtoport',port,'self,server,listcn(backlog)#Trapkeyboardinterruptssignal.signal(signal.SIGINT,self.sighandler)defsighandler(self,signum,frame):#Clo
4、setheserverprint'Shuttingdownserver...'#Closeexistingclientsocketsforoinself,outputs:o.close()self,server,close()defgetname(self,client):#Returntheprintablenameofthe#client,givenitssocket…info=self,clientmap[clicnt]host,name=info[0][0],info[l]return'.join((na
5、me,host))defserve(seif):inputs=[self,server,sys.stdin]self,outputs二[]running二1whilerunning:try:inputready,outputready,exceptreeidy=select,select(inputs,self,outputs,[])exceptselect.error,e:breakexceptsocket.em、,e:breakforsininputready:ifs二二self,server:#hemdle
6、theserversocketclient,address=self,server,accept()print'chatserver:gotconnection%dfrom%s‘%(client.filenoO,address)#Readtheloginnamecname二receive(client)•split(‘NAME:’)[1]#Computeclientnameandsendbackself,clients+二1send(client,'CLIENT:'+str(address[0]))inputs,
7、append(dient)(self,clients,dataseif.getname(s)self,dientmap[client]二(address,cname)#Sendjoininginformationtootherclientsmsg=,(Conncctcd:Newclient(%d)from%s),%self,getname(client))foroinself,outputs:#o.send(msg)send(o,msg)self,outputs,appcnd(clicnt)elifs二二sy
8、s.stdin:#handlestandardinputjunk=sys.stdin.readline()running二0else:#handleallothersocketstry:#data二s.recv(BUFSTZ)data=receive(s)ifdata:#Sendasnewclient"smessage...msg='#['+self,getname(