我有一个异步客户机,它与用C编写的服务器交互。 我需要能够检测服务器何时关闭连接,并不断尝试连接到它,直到它再次可用。 下面是我的代码: 这是我的asyncore客户机,我启动另一个线程模块(ReceiverBoard)在一个单独的线程中运行。 类DETClient(asyncore.dispatcher)公司名称:
buffer = ""
t = None
def __init__(self, host, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect((host,port))
self.host=host
self.port=port
self.t = ReceiverBoard(self)
self.t.start()
def sendCommand(self, command):
self.buffer = command
def handle_error(self):
self.t.stop()
self.close()
def handle_write(self):
sent=self.send(self.buffer.encode())
self.buffer=""
def handle_read(self):
##there is code here to parse the received message and call the appropriate
##method in the threaded module ReceiverBoard
我的第一个问题是,我希望客户机(上面的)继续尝试通过套接字连接到服务器(在ansic C中开发),直到建立连接。在
我所做的更改是重写上面asyncore中的handle_error方法,只需调用另一个方法尝试再次初始化连接,而不是关闭套接字。如下所示:(在上面的DETClient中添加了以下代码)
这解决了运行此代码时服务器不可用的问题。引发异常并调用handle_error,该错误只需调用initiate_connection方法并尝试再次打开套接字。另外,在最初建立连接之后,如果由于任何原因丢失了套接字,代码将调用handle_error,并尝试重新建立连接。 问题解决了!在
以下是线程模块(接收器板)的代码
^{pr2}$相关问题 更多 >
编程相关推荐