ZeroMQサービス側とクライアント

1752 ワード

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 wegian forest wears a tam-o-shanter Publish:siamese wears a fedora Publish:siamese wears a a a a a a tam-a tam-a tam-a tam-o-shars Publish 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))

なぜか購読で物が出ない