首页 > 代码库 > ZeroMQ-pair

ZeroMQ-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.

#pairserver.py
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
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>

--------------------------------
#console-server
(D:\anaconda) C:\Users\admin\Desktop\opt>python pairserver.py
client message to server1
client message to server2
client message to server1
client message to server2
client message to server1
client message to server2
client message to server1

#console-client
(D:\anaconda) C:\Users\admin\Desktop\opt>python pairclient.py
Server message to client3
Server message to client3
Server message to client3
Server message to client3
Server message to client3
Server message to client3




ZeroMQ-pair