如何在 ZeroMQ python 中正确声明套接字类型?

How do I properly declare socket type in ZeroMQ python?

我遇到了一个奇怪的问题。我为我的 discord 机器人开发了一个网络界面,并使用 ZeroMQ 在机器人进程和 fastAPI 进程之间进行通信。我的程序是结构化的,所以 fastAPI 进程发送一个 ZeroMQ REQ。我的 discord 机器人充当“服务器”,因为它提供信息,而 fastAPI 进程充当客户端。这个特定的方法试图让我的 discord bot 获取在线成员,然后将他们发回给请求者。这是我的代码:

服务端: (不相关的部分为简洁起见)

import asyncio

import zmq
import zmq.asyncio


async def openWebServerInterface():
    zmqctx = zmq.asyncio.Context()
    s = zmqctx.socket(zmq.REP)
    s.connect('tcp://127.0.0.1:1234')
    print('waiting on request...')
    request = await s.recv_string()
    if request == "gimmethedata":
        print("sending online people")
        s.send_string(await returnOnline())
    print("data request sent!")
    s.close()

async def returnOnline():
    message = "this will return my online members"
    return message

asyncio.run(openWebServerInterface())

客户端:

async def listenForResponse():
    await openBotConnection()
    print("logo interface opened!")
    r = zmqctx.socket(zmq.REP)
    print("socket connected, waiting for response")
    reply = await r.recv_string()
    print(reply)
    return reply

async def openBotConnection():
    s = zmqctx.socket(zmq.REQ)
    s.connect('tcp://127.0.0.1:1234')
    await s.send_string("gimmethedata")
    print("data request sent!")
    s.close()

@app.get("/")
async def root():
    print("listing for logo's response!")
    return await listenForResponse()

我收到的错误消息位于服务器程序上(没有问题 运行 "client" 程序)。错误如下:

Traceback (most recent call last):
File "E:/DiscordBotContainer/ServerSideTestFile", line 23, in <module> asyncio.run(openWebServerInterface()) File "*\AppData\Local\Programs\Python\Python38\lib\asyncio\runners.py", line 43, in run return loop.run_until_complete(main) File "*\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 616, in run_until_complete return future.result() File "E:/DiscordBotContainer/fuck it", line 9, in openWebServerInterface s = zmqctx.socket(zmq.REP) File "*\AppData\Local\Programs\Python\Python38\lib\site-packages\zmq\sugar\context.py", line 204, in socket s = self._socket_class(self, socket_type, **kwargs) File "*\AppData\Local\Programs\Python\Python38\lib\site-packages\zmq\_future.py", line 144, in __init__ self._init_io_state() File "*\AppData\Local\Programs\Python\Python38\lib\site-packages\zmq\asyncio\__init__.py", line 53, in _init_io_state self.io_loop.add_reader(self._fd, lambda : self._handle_events(0, 0)) File "*\AppData\Local\Programs\Python\Python38\lib\asyncio\events.py", line 501, in add_reader raise NotImplementedError

我的直觉让我认为这是服务器端套接字声明的问题,但我在客户端使用完全相同的语法声明套接字没有问题。

Q : "How do I properly declare socket type in ZeroMQ python?"

声明不是你的问题,REQ/REP ZeroMQ 正式行为原型的任一侧都已正确实例化,使用 .socket( { zmq.REP | zmq.REQ } ) 方法和各自的原型类型。

您的问题在于为选定的 tcp:// 传输 Class.

管理 AccessPoint ISO-OSI-L3 定义

在这里,任何已知的 ZeroMQ 原型类型的一侧必须 .bind(),而另一侧必须 .connect()。没有例外,没有借口。

因此,让您的 REQ/REP 原型中的任何一个执行 .bind() 并让另一个 .connect() 进行设置,您的设置就会起作用。这里没有其他条件。