首页 > 编程语言 > 详细

python socket实现多人聊天室

时间:2019-05-22 23:07:52      阅读:186      评论:0      收藏:0      [点我收藏+]

服务器端:

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实现多人聊天室

原文:https://www.cnblogs.com/batt1ebear/p/10909027.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!