如何重新建立与服务器的asyncore连接

时间:2013-08-12 21:09:22

标签: python client asyncore

我有一个asyncore客户端,它与用C编写的服务器交互。 我需要能够检测服务器何时关闭连接并继续重新尝试连接它,直到它再次可用。 这是我的代码: 这是我的asyncore客户端,我转向启动另一个线程模块(ReceiverBoard)以在单独的线程中运行。 class 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

我的第一个问题是我希望客户端(上面)继续重试通过套接字连接到服务器(在ANSI C中开发),直到建立连接。

1 个答案:

答案 0 :(得分:0)

我所做的更改是覆盖上面asyncore中的handle_error方法,只是调用另一个方法来尝试再次初始化连接而不是关闭套接字。如下所示:(以下代码添加到上面的DETClient)

def initiate_connection_with_server(self):
    print("trying to initialize connection with server...")
    asyncore.dispatcher.__init__(self)
    self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
    self.connect((self.host,self.port))

def handle_error(self):
    print("problem reaching server.")
    self.initiate_connection_with_server()

这解决了运行此代码时服务器不可用的问题。引发异常并调用handle_error,它只调用initiate_connection方法并尝试再次打开套接字。此外,在最初建立连接之后,如果套接字由于任何原因丢失,则代码将调用handle_error,并且将尝试重新建立连接。 问题解决了!

以下是线程模块(ReceiverBoard)的代码

class ReceiverBoard(threading.Thread):
    _stop = False           
    def __init__(self, client):
        self.client=client
        super(ReceiverBoard,self).__init__()
    def run(self):
        while True:
            block_to_send = ""
            ##code here to generate block_to_send
            self.client.sendCommand(block_to_send)

    def stop(self):
        self._stop = True
相关问题