官方使用文档:
中文翻译文档:
应答模式:
server端:
#
# Hello World server in Python
# Binds REP socket to tcp://*:5555
# Expects b"Hello" from client, replies with b"World"
#
import time
import zmq
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:5555")
while True:
# Wait for next request from client
message = socket.recv()
print("Received request: %s" % message)
# Do some 'work'
time.sleep(1)
# Send reply back to client
socket.send(b"World")

server端

client端:
#
# Hello World client in Python
# Connects REQ socket to tcp://localhost:5555
# Sends "Hello" to server, expects "World" back
#
import zmq
context = zmq.Context()
# Socket to talk to server
print("Connecting to hello world server…")
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:5555")
# Do 10 requests, waiting each time for a response
for request in range(10):
print("Sending request %s …" % request)
socket.send(b"Hello")
# Get the reply.
message = socket.recv()
print("Received reply %s [ %s ]" % (request, message))

client端

发布订阅模式:
server端:
#
# 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))

server端

client端:
#
# 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 ""
# 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
for update_nbr in range(5):
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+1))
)

client端

推拉模式:
server端:
# Task ventilator
# Binds PUSH socket to tcp://localhost:5557
# Sends batch of tasks to workers via that socket
#
# Author: Lev Givon <lev(at)columbia(dot)edu>
import zmq
import random
import time
try:
raw_input
except NameError:
# Python 3
raw_input = input
context = zmq.Context()
# Socket to send messages on
sender = context.socket(zmq.PUSH)
sender.bind("tcp://*:5557")
# Socket with direct access to the sink: used to syncronize start of batch
sink = context.socket(zmq.PUSH)
sink.connect("tcp://localhost:5558")
print("Press Enter when the workers are ready: ")
_ = raw_input()
print("Sending tasks to workers…")
# The first message is "0" and signals start of batch
sink.send(b'')
# Initialize random number generator
random.seed()
# Send 100 tasks
total_msec = 0
for task_nbr in range(100):
# Random workload from 1 to 100 msecs
workload = random.randint(1, 100)
total_msec += workload
sender.send_string(u'%i' % workload)
print("Total expected cost: %s msec" % total_msec)
# Give 0MQ time to deliver
time.sleep(1)

server端

中间work端(可有可无):
# Task worker
# Connects PULL socket to tcp://localhost:5557
# Collects workloads from ventilator via that socket
# Connects PUSH socket to tcp://localhost:5558
# Sends results to sink via that socket
#
# Author: Lev Givon <lev(at)columbia(dot)edu>
import sys
import time
import zmq
context = zmq.Context()
# Socket to receive messages on
receiver = context.socket(zmq.PULL)
receiver.connect("tcp://localhost:5557")
# Socket to send messages to
sender = context.socket(zmq.PUSH)
sender.connect("tcp://localhost:5558")
# Process tasks forever
while True:
s = receiver.recv()
# Simple progress indicator for the viewer
sys.stdout.write('.')
sys.stdout.flush()
# Do the work
time.sleep(int(s)*0.001)
# Send results to sink
sender.send(b'')

中间work端(可有可无)

client端:
# Task sink
# Binds PULL socket to tcp://localhost:5558
# Collects results from workers via that socket
#
# Author: Lev Givon <lev(at)columbia(dot)edu>
import sys
import time
import zmq
context = zmq.Context()
# Socket to receive messages on
receiver = context.socket(zmq.PULL)
receiver.bind("tcp://*:5558")
# Wait for start of batch
s = receiver.recv()
# Start our clock now
tstart = time.time()
# Process 100 confirmations
for task_nbr in range(100):
s = receiver.recv()
if task_nbr % 10 == 0:
sys.stdout.write(':')
else:
sys.stdout.write('.')
sys.stdout.flush()
# Calculate and report duration of batch
tend = time.time()
print("Total elapsed time: %d msec" % ((tend-tstart)*1000))

client端

非阻塞模式的两种实现:
原始方式中的zmq.DONTWAIT是3.0之后的版本使用,之前的版本使用zmq.NOBLOCK
import zmq
import time # Prepare our context and sockets
context = zmq.Context() # Connect to task ventilator
receiver = context.socket(zmq.PULL)
receiver.connect("tcp://localhost:5557") # Connect to weather server
subscriber = context.socket(zmq.SUB)
subscriber.connect("tcp://localhost:5556")
subscriber.setsockopt(zmq.SUBSCRIBE, b"") # Process messages from both sockets
# We prioritize traffic from the task ventilator
while True: # Process any waiting tasks
while True:
try:
msg = receiver.recv(zmq.DONTWAIT)
except zmq.Again:
break
# process task # Process any waiting weather updates
while True:
try:
msg = subscriber.recv(zmq.DONTWAIT)
except zmq.Again:
break
# process weather update # No activity, so sleep for 1 msec
time.sleep(0.001)

原始方式(不推荐)

import zmq

# Prepare our context and sockets
context = zmq.Context() # Connect to task ventilator
receiver = context.socket(zmq.PULL)
receiver.connect("tcp://localhost:5557") # Connect to weather server
subscriber = context.socket(zmq.SUB)
subscriber.connect("tcp://localhost:5556")
subscriber.setsockopt(zmq.SUBSCRIBE, b"") # Initialize poll set
poller = zmq.Poller()
poller.register(receiver, zmq.POLLIN)
poller.register(subscriber, zmq.POLLIN) # Process messages from both sockets
while True:
try:
socks = dict(poller.poll())
except KeyboardInterrupt:
break if receiver in socks:
message = receiver.recv()
# process task if subscriber in socks:
message = subscriber.recv()
# process weather update

poll方式

 
 
 
 

zeromq-python使用的更多相关文章

  1. saltstack学习笔记1 --安装

    salt官网:http://docs.saltstack.cn/zh_CN/latest/ 安装教程: - http://docs.saltstack.cn/zh_CN/latest/topics/i ...

  2. 一、saltstack简介和安装

    系统环境:CentOS6.5 准备yum源: epel源(包含了saltstack的包).阿里源(CentOS-Base.repo) Host解析文件: # cat /etc/hosts 192.16 ...

  3. 源码安装saltstack的时候遇到的问题

    公司的系统都是内网,无法连接互联网,所以没办法只有源码安装了. 看了下saltstack的官网,需要安装的包有 https://docs.saltstack.com/en/latest/topics/ ...

  4. SaltStack系列(一)之环境部署、命令及配置文件详解

    一.SaltStack介绍 1.1 saltstack简介: saltstack是基于python开发的一套C/S架构配置管理工具,它的底层使用ZeroMQ消息队列pub/sub方式通信,使用SSL证 ...

  5. saltstack配置文件详解

    软件依赖 Python版本大于2.6或版本小于3.0: 对Python版本要求 msgpack-python: SalStack消息交换库 YAML: SaltStack配置解析定义语法 Jinja2 ...

  6. ZeroMQ - 三种模型的python实现

    ZeroMQ是一个消息队列网络库,实现网络常用技术封装.在C/S中实现了三种模式,这段时间用python简单实现了一下,感觉python虽然灵活.但是数据处理不如C++自由灵活. 1.Request- ...

  7. zeromq 学习和python实战

    参考文档: 官网 http://zeromq.org/ http://www.cnblogs.com/rainbowzc/p/3357594.html   原理解读 zeromq只是一层针对socke ...

  8. 安装zeromq以及zeromq的python示例

    下载ZeroMq: wget https://github.com/zeromq/zeromq4-1/releases/download/v4.1.5/zeromq-4.1.5.tar.gz 解压: ...

  9. Qt编程可不可以结合其他的第三方库和本土API?(有zeroMQ的Qt封装,还可轻易使用Python的库)

    作者:渡世白玉链接:http://www.zhihu.com/question/29030777/answer/59378712来源:知乎著作权归作者所有,转载请联系作者获得授权. 可以,十分可以,你 ...

  10. storm安装(2)ZeroMQ、JZMQ、Python、Java环境的安装

    2.ZeroMQ安装 把安装本件zeromq-2.1.7.tar.gz拷贝到home文件路径下, 给文件加入权限 chmod +x /home/zeromq-2.1.7.tar.gz 解压文件 tar ...

随机推荐

  1. php的json_encode函数问题

    php的json_encode函数问题: $ary = []; $ary[0] = 'a'; $ary[1] = 'b'; echo json_encode($ary) . '<br>'; ...

  2. python bottle 框架开发任务管理系统 V_1.0版

    经过1-2个星期的开发,现在开发了个半成品(UI现在比较烂,因为我的前端本来就很差,将就下吧),大概功能如下:用户功能(添加.删除.修改),添加部门功能,任务管理功能(添加.删除.修改,详细).项目管 ...

  3. hdu 1208 Pascal's Travels

    http://acm.hdu.edu.cn/showproblem.php?pid=1208 #include <cstdio> #include <cstring> #inc ...

  4. UESTC_秋实大哥搞算数 2015 UESTC Training for Data Structures<Problem N>

    N - 秋实大哥搞算数 Time Limit: 3000/1000MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Others) Subm ...

  5. Trapping Raining Water 解答

    Question Given n non-negative integers representing an elevation map where the width of each bar is ...

  6. ZOJ3578(Matrix)

    Matrix Time Limit: 10 Seconds      Memory Limit: 131072 KB A N*M coordinate plane ((0, 0)~(n, m)). I ...

  7. Java Service Wrapper

    Java Service Wrapper 将Java 应用程序部署成Windows系统服务Java Service Wrapper 1 Product Overview 1 Editions 2 Me ...

  8. Redis 3.0集群 Window搭建方案

    Redis 3.0集群 Window搭建方案 1.集群安装前准备 安装Ruby环境,安装:rubyinstaller-2.3.0-x64.exe http://dl.bintray.com/onecl ...

  9. category和extensions

    catgory 允许你为一个已经存在的类增加方法,而不需要增加一个子类.而且不需要知道它内部具体的实现. 另外,虽然Category不能够为类添加新的成员变量,但是Category包含类的所有成员变量 ...

  10. Tomcat可以在eclipse里启动,可是不能訪问首页的问题

    今天在使用eclipse的时候发现一个问题.就是我在eclipse里面已经启动了tomcat.部署上去的项目也能够启动,可是就是没法訪问tomcat的首页.port等等都没有问题. 后来查到解决方式, ...