Which ZeroMQ pattern is best of an asynchronous pair of sockets?

↘锁芯ラ 提交于 2019-12-10 23:29:16

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!