PAIR

It provides sockets that are close in behavior to conventional sockets.

Conventional sockets allow:

  • only strict one-to-one (two peers)
  • many-to-one (many clients, one server)
  • one-to-many (multicast) relationships

Exclusive pair pattern

Paired sockets are very similar to regular sockets.

  • The communication is bidirectional.
  • There is no specific state stored within the socket
  • There can only be one connected peer.
  • The server listens on a certain port and a client connects to it.
../../_images/pair.png

What this really shows is the simplicity of setup and the fact that you receive the complete message that was sent. There is no need to think whether you have read the complete message or not.

pairserver.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import zmq
import random
import sys
import time

port = "5556"
context = zmq.Context()
socket = context.socket(zmq.PAIR)
socket.bind("tcp://*:%s" % port)

while True:
    socket.send("Server message to client3")
    msg = socket.recv()
    print msg
    time.sleep(1)

pairclient.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import zmq
import random
import sys
import time

port = "5556"
context = zmq.Context()
socket = context.socket(zmq.PAIR)
socket.connect("tcp://localhost:%s" % port)

while True:
    msg = socket.recv()
    print msg
    socket.send("client message to server1")
    socket.send("client message to server2")
    time.sleep(1)

running it:

python pairserver.py <port>
python pairclient.py <port>

Each of them can send any number of messages to each other.