欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python实现简单多人聊天室

程序员文章站 2022-05-11 12:34:55
本文实例为大家分享了python实现多人聊天室的具体代码,供大家参考,具体内容如下 刚开始学习python,写了一个聊天室练练手。 server.py imp...

本文实例为大家分享了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()

client.py

import socket,select,threading,sys;
 
host=socket.gethostname()
 
addr=(host,5963)
 
def conn():
  s=socket.socket()
  s.connect(addr)
  return s
 
def lis(s):
  my=[s]
  while true:
    r,w,e=select.select(my,[],[])
    if s in r:
      try:
        print s.recv(1024)
      except socket.error:
        print 'socket is error'
        exit()
      
def talk(s):
  while true:
    try:
      info=raw_input()
    except exception,e:
      print 'can\'t input'
      exit()
    try:
      s.send(info)
    except exception,e:
      print e
      exit()
      
def main():
  ss=conn()
  t=threading.thread(target=lis,args=(ss,))
  t.start()
  t1=threading.thread(target=talk,args=(ss,))
  t1.start()
if __name__=='__main__':
  main()

运行时先启动服务端。进入聊天室先起一个昵称。服务端会向客户端发送当前聊天室内聊天人的列表。一个客户端发出的消息会通过服务端发给其他客户端。

效果如下:

python实现简单多人聊天室

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。