File: reqrep.py

package info (click to toggle)
pyzmq 20.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 2,228 kB
  • sloc: python: 14,051; ansic: 941; cpp: 315; makefile: 179; sh: 32
file content (48 lines) | stat: -rw-r--r-- 1,139 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"""
Complex example which is a combination of the rr* examples from the zguide.
"""
from __future__ import print_function
from gevent import spawn
import zmq.green as zmq

# server
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.connect("tcp://localhost:5560")

def serve(socket):
    while True:
        message = socket.recv()
        print("Received request: ", message)
        socket.send("World")
server = spawn(serve, socket)


# client
context = zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:5559")

#  Do 10 requests, waiting each time for a response
def client():
    for request in range(1,10):
        socket.send("Hello")
        message = socket.recv()
        print("Received reply ", request, "[", message, "]")


# broker
frontend = context.socket(zmq.ROUTER)
backend  = context.socket(zmq.DEALER)
frontend.bind("tcp://*:5559")
backend.bind("tcp://*:5560")

def proxy(socket_from, socket_to):
    while True:
        m = socket_from.recv_multipart()
        socket_to.send_multipart(m)

spawn(proxy, frontend, backend)
spawn(proxy, backend, frontend)

spawn(client).join()