如何在C和Python端之间用nanomsg设置Pub/Sub?

2024-04-29 14:24:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习库。在

我使用了C和Python版本的代码示例。我试图用Python脚本订阅C服务,但是什么都没有发生。在

以下是我的两个代码:

Python订阅服务器

from __future__ import print_function
from nanomsg import Socket, PAIR, PUB
s2 = Socket(PAIR)
while(True):
    s2.connect('tcp://127.0.0.1:5555')
    s2.send(b'hello nanomsg #1')
    s2.send(b'hello nanomsg #2')
    s2.close()

C代码:

^{pr2}$

我运行C代码的方法是

./pubsub_demo tcp://127.0.0.1:5555 -s

谢谢你的帮助


Tags: 代码fromimport版本服务器脚本send示例
1条回答
网友
1楼 · 发布于 2024-04-29 14:24:49

C代码看起来不错。它来自here。在

CNN_PUB服务器和NN_SUB客户端的简单版本也是exists。在

提供的Python代码有一些问题。在

1)在中,我们必须匹配行为-“协议”。为了接收来自C服务器的NN_PUB广播,我们必须在Python端有一个匹配的SUB,而不是PAIR,套接字。在

2)连接到同一个端点-transport-class://address:port作为NN_PUB套接字nn_bind()-s到。没有必要在循环中这样做。在

3)套接字必须设置SUB_SUBSCRIBE选项。在

4)SUB插座是用来监听的,它不是用来.send()任何东西的。在

一个未经测试的Python程序原则上可以如下所示:

# import appropriate modules for the nanomsg socket
from nanomsg import Socket, PUB, SUB, SUB_SUBSCRIBE

# open Python's SUB socket matching the NN_PUB socket on the C side 
s2 = Socket(SUB)
# s2 should be >= 0

# connect the socket to the same endpoint as NN_PUB server
ret1 = s2.connect('tcp://127.0.0.1:5555')
# ret1 should be 0

# subscribe to everything:
ret2 = s2.set_string_option(SUB, SUB_SUBSCRIBE, '')
# ret1 should be 0

# receive messages:
while(True):
    message = s2.recv()

您还可以查看Python测试PUB/SUB example

我希望有帮助。在

相关问题 更多 >