Python JSON-RPC如何在连接处于活动状态时从客户端接收请求

时间:2020-10-28 12:17:33

标签: python websocket json-rpc

我目前正在制作通过Websocket连接使用JSON-RPC的模块。我的客户端安装程序创建了websocket连接,并将JSON-RPC请求发送到另一台运行请求的功能并返回数据的服务器。但是,我还需要客户端接收JSON-RPC请求,运行该函数,然后将数据返回给服务器。我的google-fu尚未返回任何有用的信息,我正努力寻找实现所需的东西。希望有人可以提供帮助。

以下代码是我要执行的操作的示例。从客户端向服务器发出前两个请求后,我希望从服务器接收一个请求,该请求将触发some_function(),一旦完成,它将在客户端发出另一个请求之前将结果发送回服务器到服务器。我觉得如果必须在客户端旁边创建服务器会很奇怪,因为websockets / json-rpc是两种方式...我希望有人能提供帮助。

import asyncio
import websockets
from jsonrpcclient.clients.websockets_client import WebSocketsClient


@method
async def some_function(ABC, 123):
    return {"ABC": 'donkey', "123": 'sheep'}

async def process_connection():
    async with websockets.connect('ws://localhost:5000') as ws:
       while  true:
            client = WebSocketsClient(ws)

            response = await client.request("ping")
            print(response.data.result)

            response2 = await client.request("donkey")
            print(response2.data.result)

            ※※※ RECEIVE REQUEST here

            response3 = await client.request("cow")
            print(response2.data.result)

async def main():
    # Set tasks and run
    try:
        get_data = loop.create_task(process_connection())
        await asyncio.wait([get_data])
    except Exception as e:
        print(e)


if __name__ == "__main__":
    # Set asyncio loop and run main()
    try:
        loop = asyncio.get_event_loop()
        loop.run_until_complete(main())
        loop.run_forever()
    except Exception as e:
        print(e)

0 个答案:

没有答案