从autobahn WebSocketClientProtocol到另一个对象

时间:2016-01-08 11:56:03

标签: python python-3.x python-asyncio autobahn

首先,有一个IO类,它在__init__上传递了主类中早先创建的asyncio循环对象(io = IO(loop))。 IO类然后在某个时候通过执行Socket来初始化self.socket = Socket(self)类,以便套接字对象具有向后访问权限。稍后,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_connection()创建asyncio连接,然后通过执行{{{{}}将coro future添加到循环中。 1}}。

现在,问题就出现了: 高速公路工厂需要一个必须从run_until_complete()

继承的类

我的班级autobahn.asyncio.websocket.WebSocketClientProtocol通常有:

Protocol(WebSocketClientProtocol)

这完全正常,class Protocol(WebSocketClientProtocol): @asyncio.coroutine def onOpen(self): print('socket opened!') 会打印字符串,我的服务器也说连接已打开。

问题: 从Protocol()类开始,当autobahn调用onOpen()回调时,如何让这个方法调用transport.onOpen()方法并执行print('socket opened!')

1 个答案:

答案 0 :(得分:1)

好的,所以我修好了!使用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')

<强>更新

我有另一个,IMO更好的解决方案。这个没有使用PyDispatch。由于在asyncio任务完成时有一个回调,它返回用户定义的协议对象(继承自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)