python编程练习----多用户聊天室,通信
基于python3.6实现多用户通信,简单聊天室
代码:
服务器代码:
import socket,select
connection_list = []
host = ''
port = 8000
def board_cast(sock,message):
for socket in connection_list:
if socket != server_sock and socket != sock:
try:
socket.send(message)
except:
socket.close()
print(str(socket.getpeername())+' is offline')
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(5)
connection_list.append(server_sock)
while True:
rs,ws,es = select.select(connection_list,[],[])#select�����������̣�ֱ��connection_list�����ֱ����������յ��ͻ��˷������ź�
for sock in rs:
if sock == server_sock: #����Ƿ��������ֱ�����
connection,addr = sock.accept()
message = str(addr)+'enter room'
board_cast(connection,message)
print(addr,'%s connect')
connection_list.append(connection) #connection_list����ͻ�������
else: #���ͻ��˷�������ʱ���ͻ������ֱ�������rs���ؿͻ������֣�Ȼ�������һ������
try:
date = sock.recv(1024)
print(date)
board_cast(sock,'('+str(sock.getpeername())+') :'+date)
except:
message2 = str(sock.getpeername())+ 'is offline'
board_cast(sock,message2)
print(str(sock.getpeername())+ ' is offline')
sock.close()
connection_list.remove(sock)
continue
客户端代码:
import socket,threading,time
flag = False
local = ''
lock = threading.Lock()
host = 'localhost'
port = 8000
client_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client_sock.setblocking(0)
class thread1(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
global flag, local
while True:
local = input()
if len(local):
lock.acquire()
flag = False
lock.release()
class thread2(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
global flag
global local
while True:
try:
buf = client_sock.recv(1024)
if len(buf):
print(buf)
except:
pass
if flag:
try:
client_sock.send(local)
except socket.error as e:
print(e)
lock.acquire()
flag = False
lock.release()
try:
client_sock.connect((host,port))
print("Hving connectioning!")
except socket.error as e:
print(e)
t1 = thread1()
t2 = thread2()
t1.start()
t2.start()
运行截图: