#
# Hello World server in Python
# Binds REP socket to tcp://*:5555
# Expects "Hello" from client, replies with "World"
#
import zmq
import time
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: ", message
# Do some 'work'
time.sleep (1) # Do some 'work'
# Send reply back to client
socket.send("World")
hwclient.py
#
# 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 (1,10):
print "Sending request ", request,"..."
socket.send ("Hello")
# Get the reply.
message = socket.recv()
print "Received reply ", request, "[", message, "]"
问题3:zeroMQ实现一个消息层?
答:
实现一个ZeroMQ消息层需要三个步骤:
1.选择传输协议
0MQ提供了4种不同的传输协议 INPROC an In-Process communication model IPC an Inter-Process communication model MULTICAST multicast via PGM, possibly encapsulated in UDP TCP a network based transport
2.建立基础
由于在网络中两个端点是相对动态的,很难有一个稳定的单一连接点。
如果是这种情况,可以使用由0MQ提供的转发设备。
转发设备可以绑定2个不同端口,并且转发消息从一个端点到另一个端点。
这样做的话,在网络中转发设备能够变成一个稳定的点,其它组件都可以去连接。
0MQ提供了3种类型的设备 QUEUE, a forwarder for the request/response messaging pattern FORWARDER, a forwarder for the publish/subscribe messaging pattern STREAMER, a forwarder for the pipelined messaging pattern
3.选择通讯模式
0MQ支持4种模式 REQUEST/REPLY, bidirectional, load balanced and state based PUBLISH/SUBSCRIBE, publish to multiple recipients at once UPSTREAM / DOWNSTREAM, distribute data to nodes arranged in a pipeline PAIR, communication exclusively between peers
Req/Rep
均衡负载请求:
server 1