python实现简单多人聊天室-创新互联
本文实例为大家分享了python实现多人聊天室的具体代码,供大家参考,具体内容如下
专注于为中小企业提供网站设计、成都网站建设服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业永嘉免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了成百上千家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。刚开始学习python,写了一个聊天室练练手。
Server.py
import socket,select,thread; host=socket.gethostname() port=5963 addr=(host,port) inputs=[] fd_name={} def who_in_room(w): name_list=[] for k in w: name_list.append(w[k]) return name_list def conn(): print 'runing' ss=socket.socket() ss.bind(addr) ss.listen(5) return ss def new_coming(ss): client,add=ss.accept() print 'welcome %s %s' % (client,add) wel='''welcome into the talking room . please decide your name.....''' try: client.send(wel) name=client.recv(1024) inputs.append(client) fd_name[client]=name nameList="Some people in talking room, these are %s" % (who_in_room(fd_name)) client.send(nameList) except Exception,e: print e def server_run(): ss=conn() inputs.append(ss) while True: r,w,e=select.select(inputs,[],[]) for temp in r: if temp is ss: new_coming(ss) else: disconnect=False try: data= temp.recv(1024) data=fd_name[temp]+' say : '+data except socket.error: data=fd_name[temp]+' leave the room' disconnect=True if disconnect: inputs.remove(temp) print data for other in inputs: if other!=ss and other!=temp: try: other.send(data) except Exception,e: print e del fd_name[temp] else: print data for other in inputs: if other!=ss and other!=temp: try: other.send(data) except Exception,e: print e if __name__=='__main__': server_run()
网站栏目:python实现简单多人聊天室-创新互联
文章出自:http://scgulin.cn/article/shdpo.html