Last active
March 27, 2018 08:27
-
-
Save wwj718/873f9def8e019a7f6c24a77bd88cb771 to your computer and use it in GitHub Desktop.
pub和sub在同个文件中
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import zmq | |
import time | |
from zmq.utils.strtypes import asbytes | |
import threading | |
context = zmq.Context() | |
pub = context.socket(zmq.PUB) | |
pub.bind("tcp://*:5000") | |
#context = zmq.Context() | |
sub = context.socket(zmq.SUB) | |
sub.connect("tcp://127.0.0.1:5000") | |
sub.setsockopt_string(zmq.SUBSCRIBE, "a") | |
def bg_task(): | |
while True: | |
topic, msg = sub.recv_multipart() | |
print("[sub]: topic:{};msg:{}".format(topic,msg)) | |
bg_task = threading.Thread(target=bg_task) | |
bg_task.start() | |
time.sleep(0.01) | |
topics = [b"a"] | |
for i in range(5): | |
for topic in topics: | |
msg = "Hello, {}".format(i) | |
pub.send_multipart([topic, asbytes(msg)]) | |
print("[pub]:{} topic:{};msg:{}".format(i,topic,msg)) | |
# time.sleep(5) |
不管你使用Golang库还是python库,如果你不严格保证socket的线程安全
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://github.com/zeromq/pyzmq/blob/master/examples/poll/pubsub.py#L25
休眠一秒让程序连接
其他地方只要import就行