zeromq samples getting the message out

Getting the Message Out


The second classic pattern is one-way data distribution,in which a server pushes

updates to a set of a set of clients.Let's see an example that pushes out weather

updates consisting of a zip code,temperature,and relative humidity.




Here's the server.We'll use port 5556 for this application:

wuserver: Weather update server in Python


#!/usr/bin/python
#
#        Weather update server
#       Binds PUB socket to tcp://*5556
#       Publishes random weather updates
#

import zmq 
from random import randrange

context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind("tcp://*:5556")

while True:
        zipcode = randrange(1,100000)
        temperature = randrange(-80,135)
        relhumidity = randrange(10,60)

        socket.send_string("%i %i %i" % (zipcode,temperature,relhumidity))

There's no start and no end to this stream of updates,it's like a never ending broadcast.


Here is the client application,which listens to the stream of updates and grabs anything

to do with a specified zip code,by default New York City because that's a great place to 

start any adventure:


wuserver: Weather update client in Python


#!/usr/bin/python
#
#       Weather update client
#       Connects SUB socket to tcp://localhost:5556
#       Collects weather updates and finds avg temp in zipcode
#

import sys
import zmq

#       Socket to talk to server
context = zmq.Context()
socket = context.socket(zmq.SUB)

print("Collecting updates from weather server...")
socket.connect("tcp://localhost:5556")

#Subscribe to zipcode,default is NYC,10001
zip_filter = sys.argv[1] if len(sys.argv) > 1 else "10001"

#Python 2 - ascii bytes to unicode str
if isinstance(zip_filter,bytes):
        zip_filter = zip_filter.decode('ascii')
socket.setsockopt_string(zmq.SUBSCRIBE,zip_filter)

#Process 5 updates
total_temp = 0
<span style="font-family: Arial, Helvetica, sans-serif;">for update_nbr in range(5):</span>
        string = socket.recv_string()
        zipcode,temperature,relhumidity = string.split()
        total_temp += int(temperature)

print("Average temperature for zipcode '%s' was %dF" %(
        zip_filter,total_temp / update_nbr)
)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值