Skip to content

Instantly share code, notes, and snippets.

@wwj718
Last active March 27, 2018 08:27
Show Gist options
  • Save wwj718/873f9def8e019a7f6c24a77bd88cb771 to your computer and use it in GitHub Desktop.
Save wwj718/873f9def8e019a7f6c24a77bd88cb771 to your computer and use it in GitHub Desktop.
pub和sub在同个文件中
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)
@wwj718
Copy link
Author

wwj718 commented Mar 20, 2018

https://github.com/zeromq/pyzmq/blob/master/examples/poll/pubsub.py#L25

import zmq, time

print("Running polling tets for PUB/SUB sockets...")

addr = 'tcp://127.0.0.1:5555'
ctx = zmq.Context()
s1 = ctx.socket(zmq.PUB)
s2 = ctx.socket(zmq.SUB)
s2.setsockopt(zmq.SUBSCRIBE, b'')

s1.bind(addr)
s2.connect(addr)

# Sleep to allow sockets to connect.
time.sleep(1.0)

休眠一秒让程序连接

其他地方只要import就行

@wwj718
Copy link
Author

wwj718 commented Mar 20, 2018

zmq socket不是线程安全的,注意这个大坑

不管你使用Golang库还是python库,如果你不严格保证socket的线程安全

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment