Python socket实现简单聊天室
本文实例为大家分享了Pythonsocket实现简单聊天室的具体代码,供大家参考,具体内容如下
服务端使用了select模块,实现了对多个socket的监控。客户端由于select在Windows下只能对socket使用,所以使用了多线程来实现对客户端输入和socket连接的同时监控。注意这里的socket设置为了非阻塞。这样就实现了在一个线程中同时进行socket的接收和发送。
服务器代码:
#-*-coding:utf-8-*- importsocket,select connection_list=[] host='' port=10001 defboard_cast(sock,message): forsocketinconnection_list: ifsocket!=server_sockandsocket!=sock: try: socket.send(message) except: socket.close() printstr(socket.getpeername())+'isoffline' connection_list.remove(socket) server_sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) server_sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) server_sock.setblocking(0) server_sock.bind((host,port)) server_sock.listen(10) connection_list.append(server_sock) while1: readable,writable,error=select.select(connection_list,[],[]) forsockinreadable: ifsock==server_sock: connection,connection_add=sock.accept() message=str(connection_add)+'enterroom' board_cast(connection,message) printconnection_add,'%sconnect' connection_list.append(connection) else: try: date=sock.recv(1024) printdate board_cast(sock,'('+str(sock.getpeername())+'):'+date) except: message2=str(sock.getpeername())+'isoffline' board_cast(sock,message2) printstr(sock.getpeername())+'isoffline' sock.close() connection_list.remove(sock) continue
客户端代码:
#-*-coding:utf-8-*- importsocket,threading,time flag=0 date='' lock=threading.Lock() host='localhost' port=10001 client_sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) client_sock.setblocking(0) classMythread1(threading.Thread): def__init__(self): threading.Thread.__init__(self) defrun(self): globalflag,date while1: date=raw_input() iflen(date): lock.acquire() flag=1 lock.release() classMythread2(threading.Thread): def__init__(self): threading.Thread.__init__(self) defrun(self): globalflag globaldate while1: try: buf=client_sock.recv(1024) iflen(buf): printbuf except: pass ifflag: try: client_sock.send(date) exceptsocket.error,e: printe lock.acquire() flag=0 lock.release() try: client_sock.connect((host,port)) print"连接成功" exceptsocket.error,e: printe t1=Mythread1() t2=Mythread2() t1.start() t2.start()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。