添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Report this

What is the reason for this report?

How To Work with the ZeroMQ Messaging Library

Published on December 27, 2013
O.S Tezer

By O.S Tezer

How To Work with the ZeroMQ Messaging Library

Introduction

ZeroMQ Introduction and Installation How-to before reading this tutorial.

About

ZeroMQ

This Article

How to set up Python 2.7 on CentOS 6.4 tutorial.

ZeroMQ differs in the way its sockets work. Unlike the synchronous way the regular sockets work, ZeroMQ’s socket implementation “present an abstraction of an asynchronous message queue”.

The way these sockets work depend on the type of socket chosen. And flow of messages being sent depend on the chosen patterns, of which there are four:

Request/Reply Pattern: Used for sending a request and receiving subsequent replies for each one sent.

Publish/Subscribe Pattern: Used for distributing data from a single process (e.g. publisher) to multiple recipients (e.g. subscribers).

Pipeline Pattern: Used for distributing data to connected nodes.

Exclusive Pair Pattern: Used for connecting two peers together, forming a pair.

ZeroMQ works differently than typical and traditional communication set ups. It can have either side of the link (i.e. either the server or the client) bind and wait for connections. Unlike standard sockets, ZeroMQ works by the notion of knowing that a connection might occur and hence, can wait for it perfectly well.

Client - Server Structure

DigitalOceanTutorial. To install screen on a CentOS system, remember that you can simply run: yum install -y screen.

Simple Messaging Using Request/Reply Pattern

Server Example: server.py

server.py” using nano (nano server.py) and paste the below self-explanatory contents.

import zmq
# ZeroMQ Context
context = zmq.Context()
# Define the socket using the "Context"
sock = context.socket(zmq.REP)
sock.bind("tcp://127.0.0.1:5678")
# Run a simple "Echo" server
while True:
    message = sock.recv()
    sock.send("Echo: " + message)
    print "Echo: " + message

When you are done editing, save and e xit by pressing CTRL+X followed with Y.

Client Example: client.py

client.py” using nano (nano client.py) and paste the below contents.

import zmq
import sys
# ZeroMQ Context
context = zmq.Context()
# Define the socket using the "Context"
sock = context.socket(zmq.REQ)
sock.connect("tcp://127.0.0.1:5678")
# Send a "message" using the socket
sock.send(" ".join(sys.argv[1:]))
print sock.recv()

When you are done editing, save and exit by pressing CTRL+X followed with Y.

Note: When working with ZeroMQ library, remember that each thread used to send a message (i.e. .send(..)) expects a .recv(..) to follow. Failing to implement the pair will cause exceptions.

Usage

Working with Publish/Subscribe Pattern

Publisher Example: pub.py

pub.py” using nano (nano pub.py) and paste the below contents.

import zmq
import time
# ZeroMQ Context
context = zmq.Context()
# Define the socket using the "Context"
sock = context.socket(zmq.PUB)
sock.bind("tcp://127.0.0.1:5680")
id = 0
while True:
    time.sleep(1)
    id, now = id+1, time.ctime()
    # Message [prefix][message]
    message = "1-Update! >> #{id} >> {time}".format(id=id, time=now)
    sock.send(message)
    # Message [prefix][message]
    message = "2-Update! >> #{id} >> {time}".format(id=id, time=now) 
    sock.send(message)
    id += 1

When you are done editing, save and exit by pressing CTRL+X followed with Y.

Subscriber Example: sub.py

sub.py” using nano (nano sub.py) and paste the below contents.

import zmq
# ZeroMQ Context
context = zmq.Context()
# Define the socket using the "Context"
sock = context.socket(zmq.SUB)
# Define subscription and messages with prefix to accept.
sock.setsockopt(zmq.SUBSCRIBE, "1")
sock.connect("tcp://127.0.0.1:5680")
while True:
    message= sock.recv()
    print message

When you are done editing, save and exit by pressing CTRL+X followed with Y.

Note: Using the .setsockopt(..) procedure, we are subscribing to receive messages starting with string 1. To receive all, leave it not set (i.e. "").

Usage

Pipelining the Pub./Sub. with Pipeline Pattern (Push/Pull)

PUSH Example: manager.py

manager.py” using nano (nano manager.py) and paste the below contents.

import zmq
import time
# ZeroMQ Context
context = zmq.Context()
# Define the socket using the "Context"
sock = context.socket(zmq.PUSH)
sock.bind("tcp://127.0.0.1:5690")
id = 0
while True:
    time.sleep(1)
    id, now = id+1, time.ctime()
    # Message [id] - [message]
    message = "{id} - {time}".format(id=id, time=now)
    sock.send(message)
    print "Sent: {msg}".format(msg=message)

The file manager.py will act as a task allocator.

PULL Example: worker_1.py

Usage

Exclusive Pair Pattern

Bind Example: bind.py

bind.py” using nano (nano bind.py) and paste the below contents.

import zmq
# ZeroMQ Context
context = zmq.Context()
# Define the socket using the "Context"
socket = context.socket(zmq.PAIR)
socket.bind("tcp://127.0.0.1:5696")

When you are done editing, save and exit by pressing CTRL+X followed with Y.

Connect Example: connect.py

connect.py” using nano (nano connect.py) and paste the below contents.

import zmq
# ZeroMQ Context
context = zmq.Context()
# Define the socket using the "Context"
socket = context.socket(zmq.PAIR)
socket.connect("tcp://127.0.0.1:5696")

When you are done editing, save and exit by pressing CTRL+X followed with Y.

Usage

https://twitter.com/ostezer”>O.S. Tezer</a></div>

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author

O.S Tezer
O.S Tezer
Author
Category:

Still looking for an answer?

Was this helpful?


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Great Tutorial! Best I have seen for python, puts the short tutorials available on the zmq website to shame. Thanks!

It seems there is a minor mistake in subscriber ( sub.py ) and publisher ( pub.py ). publisher uses connect function not bind function and subscriber uses bind function. Let me know If I am wrong or I am missing something. I am saying it because I set up zmq locally and tested it and it works fine

Python 3 port:

You need to use sock.send_string and convert bytes to string and vice versa when required.

server.py

import zmq
# ZeroMQ Context
context = zmq.Context()
# Define the socket using the "Context"
sock = context.socket(zmq.REP)
sock.bind("tcp://127.0.0.1:5678")
# Run a simple "Echo" server
while True:
    message = sock.recv()
    message = str(message)
    sock.send_string("Echo: " + message)
    print("Echo: " + message)

client.py

import zmq
import time
# ZeroMQ Context
context = zmq.Context()
# Define the socket using the "Context"
sock = context.socket(zmq.REQ)
sock.connect("tcp://127.0.0.1:5678")
while True: