import socket
import time
def recv(client_socket_list):
for client_socket in client_socket_list:
try:
data = client_socket.recv(1024)
except Exception as ret:
#print(ret)
print("客户端没有发来消息")
else:
if data: # 判断客户端有没有发数据过来
print(data.decode("utf-8"))
else:
print("客户端关闭对话")
client_socket.close() # 如果客户端关闭对话,那么调用client_socket.close(),并将client_socket从client_socket_list中移除,以节省内存
client_socket_list.remove(client_socket)
def main():
tcp_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM )
tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
tcp_socket.setblocking(False) # 设置套接字为非堵塞状态
tcp_socket.bind(("127.0.0.1",7890))
tcp_socket.listen(128)
client_socket_list=list()
while True:
time.sleep(1)
try: # 判断是否有客户端连接,此处因为设置了非堵塞,如果没有客户连接那么就会产生异常
client_socket,client_addr=tcp_socket.accept()
except Exception as ret:
#print(ret)
print("没有新客户连接。。。。。")
else:
print("有客户来了")
client_socket.setblocking(False) # 设置client_socket为非堵塞状态
client_socket_list.append(client_socket)
recv(client_socket_list)
tcp_socket.close()
if __name__ == "__main__":
main()
验证的时候循环中间要加time.sleep(),不然哗哗哗哗一堆根本看不见客户端发的数据在哪里