ZeroMQ服务端和客户端

zmq_pub.py

#进入虚拟环境:conda activate tf
#退出虚拟环境:conda deactivate
import zmq
import random
import time
host='*'
port=6789
ctx=zmq.Context()
pub=ctx.socket(zmq.PUB)
pub.bind('tcp://%s:%s'%(host,port))
cats=['siamese','persian','maine coon','norwegian forest']
hats=['stovepipe','bowler','tam-o-shanter','fedora']
time.sleep(1)
for msg in range(10):
    cat=random.choice(cats)
    cat_bytes=cat.encode('utf-8')
    hat=random.choice(hats)
    hat_bytes=hat.encode('utf-8')
    print('Publish: %s wears a %s'%(cat,hat))

输出:
Publish: persian wears a bowler
Publish: persian wears a stovepipe
Publish: siamese wears a tam-o-shanter
Publish: persian wears a tam-o-shanter
Publish: norwegian forest wears a bowler
Publish: norwegian forest wears a tam-o-shanter
Publish: siamese wears a fedora
Publish: siamese wears a tam-o-shanter
Publish: persian wears a tam-o-shanter
Publish: norwegian forest wears a fedora

zmq_sub.py:

import zmq
host='127.0.0.1'
port=6789
ctx=zmq.Context()
sub=ctx.socket(zmq.SUB)
sub.connect('tcp://%s:%s'%(host,port))
print('tcp://%s:%s'%(host,port))
print('tcp://{1}:{0}'.format(host,port))
topics=['maine coon','persian']
for topic in topics:
    sub.setsockopt(zmq.SUBSCRIBE,topic.encode('utf-8'))
while True:
    print('subscribe')
    cat_bytes,hat_bytes=sub.recv_multipart()
    print(cat_bytes)
    cat=cat_bytes.decode('utf-8')
    hat=hat_bytes.decode('utf-8')
    print('Subscribe: %s wears a %s'%(cat,hat))

不知道为什么订阅输不出来东西

你可能感兴趣的:(ZeroMQ服务端和客户端)