Python 从autobahn WebSocketClientProtocol回调到另一个对象

Python 从autobahn WebSocketClientProtocol回调到另一个对象,python,python-3.x,python-asyncio,autobahn,Python,Python 3.x,Python Asyncio,Autobahn,首先,有一个IO类,它在\uuuuu init\uuuuu上被传递一个异步IO循环对象(IO=IO(loop)),该对象在主类的前面创建IOclass然后在某个点通过执行self.Socket=Socket(self)初始化Socket类,以便Socket对象具有向后访问权限。稍后,Socket类初始化Websocket类,它是Transport class Websocket(Transport): name = 'websocket' def __init__(self,

首先,有一个
IO
类,它在
\uuuuu init\uuuuu
上被传递一个异步IO循环对象(
IO=IO(loop)
),该对象在主类的前面创建
IO
class然后在某个点通过执行
self.Socket=Socket(self)
初始化
Socket
类,以便Socket对象具有向后访问权限。稍后,
Socket
类初始化
Websocket
类,它是
Transport

class Websocket(Transport):

    name = 'websocket'

    def __init__(self, socket):
        self.socket = socket

    def open(self):
        url = self.prepareUrl()

        factory = WebSocketClientFactory(url, debug = False)
        factory.protocol = Protocol

        websocket = self.socket.loop.create_connection(factory, host=self.socket.io.options.host, port=self.socket.options.port)

        self.socket.io.loop.run_until_complete(websocket)

    def onOpen(self):
        print('print me please!')
因此,套接字对象调用创建高速公路工厂的
self.transport.open()
(其中
self.transport=Websocket(self)
),通过执行
self.socket.loop.create\u connection()
创建异步IO连接,然后通过执行
run\u直到完成()
将coro未来添加到循环中

现在,问题就从这里开始: autobahn工厂需要一个类,该类必须从autobahn.asyncio.websocket.WebSocketClientProtocol继承

我的类
协议(WebSocketClientProtocol)
具有通常的:

class Protocol(WebSocketClientProtocol):

    @asyncio.coroutine
    def onOpen(self):
        print('socket opened!')
这工作得非常好,
打印('socketopened!')
会打印字符串,我的服务器也会说连接已打开

问题是:
在Protocol()类中,当autobahn调用onOpen()回调时,如何使此方法调用transport.onOpen()方法并执行
print('print me please!')

确定,因此我修复了它!使用PyDispatch模块轻松完成

以下是我的解决方案:

import asyncio
from pydispatch import dispatcher
from autobahn.asyncio.websocket import WebSocketClientProtocol, WebSocketClientFactory

from ..transport import Transport

class Websocket(Transport):

    name = 'websocket'

    def __init__(self, socket):
        self.socket = socket

    def open(self):
        url = self.prepareUrl()

        factory = WebSocketClientFactory(url, debug = False)
        factory.protocol = Protocol

        websocket = self.socket.loop.create_connection(factory, host=self.socket.io.options.host, port=self.socket.options.port)

        dispatcher.connect(self.onOpen, signal='open', sender=dispatcher.Anonymous)

        self.socket.io.loop.run_until_complete(websocket)

    def onOpen(self):
        print('print me please!')


class Protocol(WebSocketClientProtocol):

    @asyncio.coroutine
    def onOpen(self):
        dispatcher.send(signal='open')
更新

我有另一个更好的解决办法。这一个没有使用PyDispatch。由于异步IO任务完成时会有一个回调,返回用户定义的协议对象(从WebSocketClientProtocol继承),因此我们可以使用该回调将两个对象链接在一起:

import asyncio
from autobahn.asyncio.websocket import WebSocketClientProtocol, WebSocketClientFactory

from ..transport import Transport

class Protocol(WebSocketClientProtocol):

    def __init__(self):
        self.ws = None
        super().__init__()

    @asyncio.coroutine
    def onConnect(self, response):
        pass # connect handeled when SocketIO 'connect' packet is received

    @asyncio.coroutine
    def onOpen(self):
        self.ws.onOpen()

    @asyncio.coroutine
    def onMessage(self, payload, isBinary):
        self.ws.onMessage(payload=payload, isBinary=isBinary)

    @asyncio.coroutine
    def onClose(self, wasClean, code, reason):
        if not wasClean:
            self.ws.onError(code=code, reason=reason)

        self.ws.onClose()           

class Websocket(Transport):

    name = 'websocket'

    def __init__(self, socket, **kwargs):
        super().__init__(socket)

        loop = kwargs.pop('loop', None)
        self.loop = loop or asyncio.get_event_loop()

        self.transport = None
        self.protocol = None

        self.ready = True

    def open(self):
        url = self.prepareUrl()
        if bool(self.socket.options.query):
            url = '{0}?{1}'.format(url, self.socket.options.query)

        factory = WebSocketClientFactory(url=url, headers=self.socket.options.headers)
        factory.protocol = Protocol

        coro = self.loop.create_connection(factory, host=self.socket.options.host, port=self.socket.options.port, ssl=self.socket.options.secure)

        task = self.loop.create_task(coro)
        task.add_done_callback(self.onWebSocketInit)

    def onWebSocketInit(self, future):
        try:
            self.transport, self.protocol = future.result()
            self.protocol.ws = self
        except Exception:
            self.onClose()

    def send(self, data):
        self.protocol.sendMessage(payload=data.encode('utf-8'), isBinary=False)
        return self

    def close(self):
        if self.isOpen:
            self.protocol.sendClose()
        return self

    def onOpen(self):
        super().onOpen()
        self.socket.setBuffer(False)

    def onMessage(self, payload, isBinary):
        if not isBinary:
            self.onData(payload.decode('utf-8'))
        else:
            self.onError('Message arrived in binary')

    def onClose(self):
        super().onClose()
        self.socket.setBuffer(True)

    def onError(self, code, reason):
        self.socket.onError(reason)

到目前为止,我找到的唯一解决方案是在循环对象中引用socket对象,这样,从
协议.onOpen()
协同程序中,我可以执行类似于
self.factory.loop.socket.transport.onOpen()的操作。为了让事情变得更漂亮,我可以将loop对象作为基线传递,它的结构类似于
loop.io.socket.transport
。但是,循环对象是否真的打算在其内部保存第三方引用?对我来说,这看起来有点太粗糙了…在cpp中,我使用了signals2来实现类似的目的,出于某种原因,我这次试图搜索python中的术语“signals”…当然没有找到任何相关的。。。现在,我正在调查PyDispatcher和其他人。如果在我找到一个足够好的解决方案之前没有人发帖,我会自己回答问题。我想我现在走对了方向。