背景
我有一个简单的套接字服务器设置,我试图允许同时连接并回显数据。客户端启动几个线程,每个线程都与服务器建立自己的连接。这适用于 socket.send() 调用,但所有后续调用都会导致“对等连接重置”或“管道损坏”。请注意,我没有找到切换重置和损坏管道的更改。我已经在这里寻找解决方案,但恐怕我可能不知道要搜索什么。
我是以错误的方式解决这个问题,还是我忽略了我的设置中的某些东西?
服务器
import SocketServer
class MyTCPHandler(SocketServer.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024).strip()
print "{} wrote: {}\n".format(self.client_address[0], self.data)
self.request.send(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
客户
import socket
import sys
import threading
import time
HOST, PORT = "localhost", 9999
def create_client():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
cur_thread = threading.current_thread()
sock.connect((HOST, PORT))
for x in range(55):
msg = "{}: {}\n".format(cur_thread.name, str(x))
# Connect to server and send data
print cur_thread.name + ": sending message\n"
sock.send(msg)
# Receive data from the server and shut down
received = sock.recv(2048)
print "RX:" + received
finally:
cur_thread = threading.current_thread()
response = "{}: Closing!\n".format(cur_thread.name)
print response
sock.close()
if __name__ == "__main__":
print "testing single thread"
#create_client()
print "starting threads"
client_1 = threading.Thread(target=create_client)
client_1.daemon = True
client_1.start()
client_2 = threading.Thread(target=create_client)
client_2.daemon = True
client_2.start()
time.sleep(20)