基于WLAN的Python-ZMQ示例

2024-04-23 23:04:41 发布

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

对于一个项目,我需要通过WLAN网络上的ZMQ在C++和Python之间通信。 如果我用C++实现,一切都很好。我只需在服务器上输入IP+端口号客户端绑定(“tcp://…)我可以通过WLAN发送消息。 如果我对Python代码进行同样的尝试,它将不起作用。你知道吗

所以我刚刚测试了Python例子(所以不再有C++):http://zguide.zeromq.org/py:durapubhttp://zguide.zeromq.org/py:durasub

我将客户机中的>;localhost<;替换为主机的IP。我没有收到任何消息。我使用的正是示例中的代码,除了替换代码。你知道吗

代码如下:

发布者:

import zmq
import time

context = zmq.Context()

# Subscriber tells us when it's ready here
sync = context.socket(zmq.PULL)
sync.bind("tcp://*:5564")

# We send updates via this socket
publisher = context.socket(zmq.PUB)
publisher.bind("tcp://*:5565")

# Wait for synchronization request
sync_request = sync.recv()

# Now broadcast exactly 10 updates with pause
for n in xrange(10):
    msg = "Update %d" % n
    publisher.send(msg)
    time.sleep(1)

publisher.send("END")
time.sleep(1)  # Give 0MQ/2.0.x time to flush output

订户

import zmq
import time

context = zmq.Context()

# Connect our subscriber socket
subscriber = context.socket(zmq.SUB)
subscriber.setsockopt(zmq.IDENTITY, "Hello")
subscriber.setsockopt(zmq.SUBSCRIBE, "")
subscriber.connect("tcp://192.168.2.119:5565")

# Syncronize with the publisher
sync = context.socket(zmq.PUSH)
sync.connect("tcp://192.168.2.119:5564")
sync.send("")

# Get updates, expect random Ctrl-C death
while True:
    data = subscriber.recv()
    print data
    if data == "END":
        break

这正是示例代码,只是我在订阅服务器代码中将localhost更改为发布服务器的IP地址。顺便说一下,我在C++示例代码中也做了同样的工作。你知道吗


Tags: 代码import服务器send示例datatimecontext