我正在努力解决以下错误:
“socket.error:[10053]'软件 导致连接中止'“
追踪(最近的呼叫最后):... self.send(json.dumps([0x02,subItems])+“\ n”)... sent = self.handler.send(data)socket.error:[Errno 10053]
我建立了服务器,我可以连接到它,发送“hello”消息,然后我可以再发送一个0x1类型的消息。服务器端未看到下一个客户端操作。客户端程序抛出socket.error。
import SocketServer
class ThreadedTCPRequestHandler(SocketServer.StreamRequestHandler):
def handle(self):
#data = json.loads(self.request.recv(1024))
if(self.request in subengine.sub.get_all_sub()):
pass
else:
#login = json.loads(self.request.recv(1024))
login = json.loads(self.rfile.readline().strip())
logging.debug("User : %s connected" % login )
data = json.loads(self.rfile.readline().strip())
if(data[0]==0x1): # subscribe
logging.info("subscribe message received, from %d" % self.request.fileno())
logging.info("symbols to subscribe: %s" % data[1])
elif (data[0] == 0x2): # unsubscribe
logging.info("unsubscribe message received")
else:
pass
# def finish(self):
# logging.info("terminating connection")
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
server = ThreadedTCPServer(('localhost',5555), ThreadedTCPRequestHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.setDaemon(True)
server_thread.start()
客户端代码示例:
class Client:
handler = None
def __init__(self, uname = '', host = 'localhost', port = 0, sock = None):
if sock is None:
self.handler = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.host = host
self.port = port
self.uname = uname
def feed_conection(self):
self.handler.connect((self.host, self.port))
if(self.handler != 0):
self.handler.send(json.dumps(self.uname)+"\n")
else:
print ("Nie udalo sie polaczyc")
def sub(self, subItems):
self.send(json.dumps([0x01, subItems])+"\n")
def unsub(self, subItems):
self.send(json.dumps([0x02, subItems])+"\n")
def send(self, data):
data_len = len(data)
total_sent = 0
while(total_sent < data_len):
sent = self.handler.send(data)
if not sent:
break
data = data[sent:]
total_sent += sent
答案 0 :(得分:0)
如果您报告的话,这实际上是您的主服务器代码结束的方式......:
server_thread.setDaemon(True)
server_thread.start()
然后你的代码说:让server_thread
在主线程死亡时死掉,让server_thread
启动,现在让主线程死掉 - 也就是说,你真的“掉线了吗? “在start
一个守护程序的线程之后?这是错的 - 一旦操作系统切换回你的主线程,繁荣,服务器端的一切就会死掉,就像你编程一样(当然,客户端代码试图继续与该服务器的对话会发现问题! - )。你为什么要让server_thread
成为一个守护进程然后让主线程结束呢?也许你并没有真正发布你正在使用的实际代码......?