问题
I have a server (running on Amazon) and a single client that connects to it. After a connect has been established the client and server exclusively communicate with each other and send messages.
e.g.
1. Client -> Server
2. Client -> Server
3. Client <- Server
4. Client -> Server
5. Client <- Server
6. Client <- Server
The client might lost connectivity and re-connect after some time and resume message sending. Also what are the implications of the order of messages? Could #2 arrive before #1?
回答1:
Push/pull is best in this situation. It will allow async messaging, but will store messages if a endpoint drops away for a time.
For ordering, ZeroMQ is a abstraction of a FIFO queue and is built over TCP. This will ensure that all messages are passed up to the application in the order that they're received.
回答2:
To add a bit to the existing answer (as it has an upvoted comment asking for elaboration), one solution could be to set up two sockets on each node. Here's an example where we send messages using input
while listening for responses on a background thread:
server.py
:
import zmq
import threading
context = zmq.Context()
send_socket = context.socket(zmq.PUSH)
send_socket.bind('tcp://*:5556')
def print_incoming_messages():
recv_socket = context.socket(zmq.PULL)
recv_socket.bind('tcp://*:5557')
while True:
msg = recv_socket.recv_string()
print(f'Message from client: {msg}')
# Print incoming messages in background
recv_thread = threading.Thread(target=print_incoming_messages)
recv_thread.start()
while True:
msg = input('Message to send: ')
send_socket.send_string(msg)
client.py
:
import zmq
import threading
context = zmq.Context()
send_socket = context.socket(zmq.PUSH)
send_socket.connect('tcp://127.0.0.1:5557')
def print_incoming_messages():
recv_socket = context.socket(zmq.PULL)
recv_socket.connect('tcp://127.0.0.1:5556')
while True:
msg = recv_socket.recv_string()
print(f'Message from server: {msg}')
recv_thread = threading.Thread(target=print_incoming_messages)
recv_thread.start()
while True:
msg = input('Message to send: ')
send_socket.send_string(msg)
来源:https://stackoverflow.com/questions/21946289/which-zeromq-pattern-is-best-of-an-asynchronous-pair-of-sockets