官方使用文档:
中文翻译文档:
应答模式:
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. PROCEDURE_监测系统_数据备份存储过程—备份原始数据,每十分钟一条,取平均值

    create or replace procedure proc_backup_originaldata(retCode out varchar2, -- 返回码                    ...

  2. windows下cmd导入与导出mysql 数据库

    一.导出数据库 假设导到C:\ordersys.sql 1.CMD下:输入mysqldump -u 用户名 -p 导出的数据库名>c:\ordersys.sql 2.CMD会提示输入密码:输入密 ...

  3. Happy 2004(快速幂+乘法逆元)

    Happy 2004 问题描述 : Consider a positive integer X,and let S be the sum of all positive integer divisor ...

  4. Taglib、EL、OGNL

    Taglib.EL.OGNL 阅读目录 1. Taglib(tag library) 标签库 2. EL(Expression Language) 表达式 3. OGNL(Object-Graph N ...

  5. javaScript中小数取整,四种方法的比较

    1.parseInt:只取整数位例如:parseInt(3.7) 取整结果为:3parseInt(-1.1) 取整结果为:-1 2.Math.floor :向下去整,取大的整数例如:Math.floo ...

  6. 在Cocos2d-X中新建Android项目

    Windows下创建Cocos2d-X的Android项目并不复杂,关键是要改几个环境变量 一.进入Cocos2d-X主目录修改“create-android-project.bat” 大家都知道要点 ...

  7. hdu Buy the Ticket

    import java.math.BigInteger; import java.util.*; public class Main { public static void main(String ...

  8. Codeforces 474D Flowers dp(水

    题目链接:点击打开链接 思路: 给定T k表示T组測试数据 每组case [l,r] 有2种物品a b.b物品必须k个连续出现 问摆成一排后物品长度在[l,r]之间的方法数 思路: dp[i] = d ...

  9. [Redux] Generating Containers with connect() from React Redux (FooterLink)

    Code to be refactored: class FilterLink extends Component { componentDidMount() { const { store } = ...

  10. linux系统如何限制其他用户登录

    用root 用户登录到系统排查问题,这个时候不希望别的账户登录到系统,你如何处理? vim /etc/nologin 将账号添加到此文件中去,你会发现其他用户都无法登录,报错信息如下:即连接即中断.