python實(shí)現(xiàn)簡(jiǎn)單多人聊天室-創(chuàng)新互聯(lián)

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

專注于為中小企業(yè)提供網(wǎng)站設(shè)計(jì)、成都網(wǎng)站建設(shè)服務(wù),電腦端+手機(jī)端+微信端的三站合一,更高效的管理,為中小企業(yè)永嘉免費(fèi)做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動(dòng)了成百上千家企業(yè)的穩(wěn)健成長(zhǎng),幫助中小企業(yè)通過網(wǎng)站建設(shè)實(shí)現(xiàn)規(guī)模擴(kuò)充和轉(zhuǎn)變。

剛開始學(xué)習(xí)python,寫了一個(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://www.muchs.cn/article30/shdpo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供Google、標(biāo)簽優(yōu)化、用戶體驗(yàn)、品牌網(wǎng)站建設(shè)、做網(wǎng)站、App開發(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í)需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站建設(shè)