从网上摘抄了代码,改了改,想做一个连接自动回复,但是压力测试时发现,几个请求之后卡死不动了。开新的客户也不回复。
#server
import socket
import threading
client_flag=0
def client1(socket_tcp_server):
global client_flag
new_client_socket, client_addr = socket_tcp_server.accept() #当服务器得到客户端请求连接时,client_flag=1
client_flag=1
print("客户端连接成功",client_addr)
send_date = "收到"
new_client_socket.send(send_date.encode("gbk"))
new_client_socket.close()
print("对方已经结束了会话,等待新的连接")
def main():
global client_flag
socket_tcp_server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
socket_addr=("127.0.0.1",1080)
socket_tcp_server.bind(socket_addr)
socket_tcp_server.listen(128)
print("等待一个新客户端连接....")
client1_threading = threading.Thread(target=client1, args=(socket_tcp_server,))
client1_threading.start()
while True:
if client_flag:
client1_threading = threading.Thread(target=client1,args=(socket_tcp_server,)) #新建一个线程
client1_threading.start()
client_flag = 0
if __name__ =='__main__':
main()
#locate
import socket
import threading
class receive:
def main(server_ip,server_port):
socket_tcp_client=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #创建一个套接字
server_addr=(server_ip,int(server_port))
socket_tcp_client.connect(server_addr)# 2.绑定连接
recv_date = socket_tcp_client.recv(1024) #接收信息,每次最大为1024
print("接收到的数据为:", recv_date.decode("gbk")) #decode为解码,gbk为解码方式
if __name__ =='__main__':
while True:
receive.main("127.0.0.1",1080)
测试发现可能是client_flag太快没反应过来。