您的位置:首页 > 其它

zeromq samples getting the message out

2015-04-11 16:40 85 查看
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)
)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐