本文實例為大家分享了python實現(xiàn)多人聊天室的具體代碼,供大家參考,具體內(nèi)容如下
專注于為中小企業(yè)提供網(wǎng)站設(shè)計、成都網(wǎng)站建設(shè)服務(wù),電腦端+手機端+微信端的三站合一,更高效的管理,為中小企業(yè)永嘉免費做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動了成百上千家企業(yè)的穩(wěn)健成長,幫助中小企業(yè)通過網(wǎng)站建設(shè)實現(xiàn)規(guī)模擴充和轉(zhuǎn)變。剛開始學(xué)習(xí)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()