python socket实现多人聊天室

时间:2021-11-13 10:18:16

服务器端:

import socket
import select
import threading
import time

ss = socket.socket(
            socket.AF_INET, socket.SOCK_STREAM) 
host=socket.gethostname()#本地ip
port=9999
addr=(host,port)
ss.bind(addr)
ss.listen(5)#最多监听5个
print('runing server')

fd_name={}
SL=[]
SL.append(ss)

while True:
    r,w,e=select.select(SL,[],[])#python的select函数 select的三个列表分别表示发生变化的socket,没变化的,以及出错的 交给r,w,e
    for temp in r:
        if temp is ss:#ss变化说明有新连接
                connection,address = temp.accept()
                print('new connection address:',address)
                SL.append(connection)#将新连接加入SL
                name=connection.recv(1024).decode('utf-8')#记得将传来的比特流转成字符
                fd_name[connection]=name

                ###
        else:#
            disconnect=False
            try:
                #
                thetime=time.asctime( time.localtime(time.time()) )
                data=temp.recv(1024).decode('utf-8')
                data=thetime+'\n'+fd_name[temp]+':'+data+'\n\n'
            except socket.error:
                    data=fd_name[temp]+' leave the room\n'
                    disconnect=True

            if disconnect:
                    SL.remove(temp)
                    print(data)
                    for other in SL:
                        if other!=ss and other!=temp:
                            try:
                                other.send(data.encode('utf-8'))
                            except Exception(e):
                                print(e)                    
                    del fd_name[temp]

            else:
                print(data)
                for other in SL:
                    if other!=ss:
                        try:
                            other.send(data.encode('utf-8'))
                        except Exception(e):
                            print(e)    
               

                
client.py:

import socket import
select import threading import time def lis(s): my=[s] while True: r,w,e=select.select(my,[],[]) if s in r: try: print(s.recv(1024).decode('utf-8')) except socket.error: print('socket is error') exit() def talk(s): while True: try: info=input('>>>') except Exception(e): print('can\'t input') exit() try: s.send(info.encode('utf-8')) except Exception(e): print(e) exit() ss=socket.socket(socket.AF_INET, socket.SOCK_STREAM) host=socket.gethostname()#因为是本机 addr=(host,9999) try: ss.connect(addr) print('welcome.please enter your name.....') except Exception(e): print('connection failed') exit() t=threading.Thread(target=lis,args=(ss,)) t.start() t1=threading.Thread(target=talk,args=(ss,)) t1.start() #双线程边监听边接受发送

python socket实现多人聊天室

python socket实现多人聊天室