当 Pyro4 客户端意外断开连接时释放资源

Releasing resources when Pyro4 client disconnects unexpectedly

我有一个 Pyro4 分布式系统,多个客户端连接到一个服务器。这些客户端连接到一个远程对象,该对象可能会在系统中分配一些资源(在我的例子中是虚拟设备)。

一旦客户端断开连接(假设是因为崩溃),我需要释放那些资源。检测特定客户端已与特定对象断开连接的正确方法是什么?

我尝试过不同的东西:

我添加了我当前的解决方案作为答案,但我真的很想知道是否有更优雅的方式使用 Pyro4 来执行此操作,因为这种情况是网络编程中的常见模式。

我在客户端使用 Proxy._pyroHandshake 属性作为客户端 ID,并覆盖 Daemon.validateHandshakeDaemon.clientDisconnected。这样,在每个新连接上,我将握手数据(每个客户端唯一)映射到一个连接。但我真的很想知道在 Pyro4 中是否有一种优雅的方式来做到这一点,这是网络编程中经常发生的模式。

请注意,除了使用代理作为客户端的属性,客户端还可以扩展 Pyro4.Proxy 并使用 _pyroAnnotations 将客户端 ID 发送到所有远程调用。

class Client:

    def __init__(self):

        self._client_id = uuid.uuid4()
        self._proxy = Pyro4.Proxy("PYRO:server@127.0.0.1")
        self._proxy._pyroHandshake = self._client_id
        self._proxy._pyroBind()

    def allocate_resource(self, resource_name):
        self._proxy.allocate_resource(self._client_id, resource_name)


class Server:

    def __init__(self):

        self._client_id_by_connection = {}
        self._resources_by_client_id = {}

    def client_connected(self, connection, client_id):

        self._client_id_by_connection[client_id] = connection
        self._resources_by_client_id[client_id] = []

    def client_disconnected(self, connection):

        client_id = self._client_id_by_connection[connection]

        for resource in self._resources_by_client_id[client_id]
            resource.free()

    @Pyro4.expose
    def allocate_resource(self, client_id, resource_name)

        new_resource = Resource(resource_name)
        self._resources_by_client_id[client_id].append(new_resource)

server = Server()
daemon.register(server, objectId="server")
daemon.clientDisconnect = server.client_disconnected
daemon.validateHandshake = server.client_connected
daemon.requestLoop()

Pyro 4.63 可能会为此提供一些内置支持,使其更容易实现。你可以在这里 http://pyro4.readthedocs.io/en/latest/tipstricks.html#automatically-freeing-resources-when-client-connection-gets-closed 阅读它,如果你从 Github 克隆当前的母版,你可以尝试一下。或许您可以看看这是否会使您的用例更简单?