本文實(shí)例為大家分享了python實(shí)現(xiàn)多人聊天室的具體代碼,供大家參考,具體內(nèi)容如下

剛開(kāi)始學(xué)習(xí)python,寫(xiě)了一個(gè)聊天室練練手。
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()
網(wǎng)頁(yè)標(biāo)題:python實(shí)現(xiàn)簡(jiǎn)單多人聊天室-創(chuàng)新互聯(lián)
網(wǎng)站網(wǎng)址:http://chinadenli.net/article30/shdpo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供Google、標(biāo)簽優(yōu)化、用戶體驗(yàn)、品牌網(wǎng)站建設(shè)、做網(wǎng)站、App開(kāi)發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容