结合2个基于asyncio的代码段

时间:2018-04-11 21:55:40

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

我正在使用Autobahn asyncio系统(谈论Websocket WAMP协议),它工作正常,我可以处理传入的RPC调用和pubsub。 我的问题是,我现在必须连接TCP套接字,并在通过Autobahn部分进入RPC调用时立即通过这些套接字发送信息。

高速公路部分的工作原理如下:

from autobahn.asyncio.component import Component, run
from asyncio import sleep
from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner

@comp.on_join
async def joined(session, details):
    print("Connected to websocket")

    def on_message(msg):
        msg = json.loads(msg)
        print(msg)

    def some_rpc(with_data):
        print("Doing something with the data")
        return json.dumps({'status': 'OK'})

    try:
        session.subscribe(on_message, u'some_pubsub_topic')
        session.register(some_rpc, u'some_rpc_call')
        print("RPC and Pubsub initialized")

    except Exception as e:
        print("could not subscribe to topic: {0}".format(e))

if __name__ == "__main__":
     run([comp])

但是现在我需要能够连接到多个常规TCP套接字:

class SocketClient(asyncio.Protocol):
    def __init__(self, loop):
        self.data = b''
        self.loop = loop

    def connection_made(self, transport):
        self.transport = transport
        print('connected')

    def data_received(self, data):
        print('Data received: {!r}'.format(data.decode()))

    def send(self, data):
        self.transport.write(data)

    def connection_lost(self, exc):
        print('The server closed the connection')
        print('Stop the event loop')
        self.loop.stop()

loop = asyncio.get_event_loop()

c=loop.create_connection(lambda: SocketClient(loop),
                              '192.168.0.219', 6773)
loop.run_until_complete(c)
loop.run_forever()
loop.close()

问题在于,当我将两者结合起来并执行此操作时:

def some_rpc(with_data):
    c.send('test')
    return json.dumps({'status': 'OK'})

它对我咆哮并告诉我:

  

StopIteration异常

     

在处理上述异常期间,发生了另一个异常:

     

Traceback(最近一次调用最后一次):文件   “/usr/lib/python3.5/site-packages/autobahn/wamp/websocket.py”,一行   95,在onMessage上       self._session.onMessage(msg)文件“/usr/lib/python3.5/site-packages/autobahn/wamp/protocol.py”,行   894,在onMessage上       on_reply = txaio.as_future(endpoint.fn,* invoke_args,** invoke_kwargs)文件“/usr/lib/python3.5/site-packages/txaio/aio.py”,第400行,   as_future       返回create_future_error(create_failure())文件“/usr/lib/python3.5/site-packages/txaio/aio.py”,第393行,   create_future_error       拒绝(f,错误)文件“/usr/lib/python3.5/site-packages/txaio/aio.py”,第462行,拒绝       future.set_exception(error.value)文件“/usr/lib64/python3.5/asyncio/futures.py”,第365行,在set_exception中       提出TypeError(“StopIteration与生成器交互不良”TypeError:StopIteration与生成器交互不良,不能   成长为未来

有没有人知道如何从RPC调用函数中调用send函数?

1 个答案:

答案 0 :(得分:0)

在此代码中:

unname

c=loop.create_connection(lambda: SocketClient(loop), '192.168.0.219', 6773) # [...] def some_rpc(with_data): c.send('test') return json.dumps({'status': 'OK'}) is a coroutine function,因此create_connection包含一个协程对象。这样的对象确实有c方法,但与通过网络发送内容完全无关。在调用send之后,您可能希望通过以下方式获得生成的传输:

create_connection

然后使用transport.write(),而不是transport, ignore = loop.run_until_complete(c)

相关问题