pyzmq
pyzmq copied to clipboard
ROUTER-ROUTER communication example
Here is an example of a ROUTER-ROUTER communication for anyone who is building a P2P application and needs a socket that is able to connect to several other peers simultaneously, while also being able to receive messages. I'm posting this here because I didn't find an example anywhere and it might be useful for someone.
The program takes two arguments:
- "s" or "c", meaning server or client.
- If the first argument is "c", then this argument is used as the identity of the peer. Can be any string.
Note that starting the program as a server sets the peer identity in the connection as "server".
import zmq
import sys
context = zmq.Context()
socket = context.socket(zmq.ROUTER)
if sys.argv[1] == "s":
socket.setsockopt_string(zmq.IDENTITY, 'server')
socket.bind("tcp://*:4000")
while True:
print("waiting for msg")
req = socket.recv_multipart()
print(req)
# identity of receptionist empty frame message content
socket.send_multipart([req[0], bytes(), bytes("whatup", encoding="utf-8")])
elif sys.argv[1] == "c":
socket.setsockopt_string(zmq.IDENTITY, sys.argv[2])
socket.connect("tcp://localhost:4000")
while True:
input("enter to send msg")
# identity of receptionist empty frame message content
socket.send_multipart([bytes("server", encoding="utf-8"), bytes(), bytes("cheers", encoding="utf-8")])
rep = socket.recv_multipart()
print(rep)
# In real applications do not forget to disconnect when the connection is not needed anymore
Well, I've been spoiling to put in an example of aiowire, so I've created PR #1652 to add this example into the asyncio examples subdirectory. From your comments above, I assume you intended to use CC0 (public domain copyright).
How would this example look with CURVE encryption?
In my code I'm setting:
socket.setsockopt(zmq.CURVE_SERVER, True)
socket.setsockopt(zmq.CURVE_SECRETKEY, secret_key)
socket.setsockopt(zmq.CURVE_PUBLICKEY, public_key)
socket.setsockopt(zmq.CURVE_SERVERKEY, public_key)
but then I get
File "Router.py", line 762, in connect
socket.connect(socket_path)
File "/usr/lib/python3/dist-packages/zmq/sugar/socket.py", line 251, in connect
super().connect(addr)
File "zmq/backend/cython/socket.pyx", line 595, in zmq.backend.cython.socket.Socket.connect
File "zmq/backend/cython/checkrc.pxd", line 28, in zmq.backend.cython.checkrc._check_rc
zmq.error.ZMQError: Invalid argument