zeromq / libzmq

ZeroMQ core engine in C++, implements ZMTP/3.1
https://www.zeromq.org
Mozilla Public License 2.0
9.71k stars 2.35k forks source link

Socket option for dropping older message when high watermark is reached #4414

Open shirok1 opened 2 years ago

shirok1 commented 2 years ago

Hello team, I'm currently using ZeroMQ for real-time communication library. However, sometimes the network bandwidth is restricted and cause message stuck on server queue. I wonder if there is an option that I can choose to drop older message instead of latest ones for latency consideration?

ljluestc commented 3 days ago

import zmq
import time
import random

def run_publisher():
    context = zmq.Context()
    socket = context.socket(zmq.PUB)
    socket.bind("tcp://*:5555")

    # Set the High Water Mark (HWM)
    socket.setsockopt(zmq.SNDHWM, 10)  # Set HWM to 10 messages

    print("Publisher is running...")

    message_count = 0
    while True:
        # Create a new message
        message = f"Message {message_count}"
        message_count += 1

        # Attempt to send the message
        try:
            socket.send_string(message, zmq.NOBLOCK)  # Send without blocking
            print(f"Sent: {message}")
        except zmq.Again:
            # Socket is full, drop the oldest message logic here
            print("Socket is full, dropping the oldest message.")

        # Simulate some delay
        time.sleep(random.uniform(0.1, 0.5))  # Random delay between sends

if __name__ == "__main__":
    run_publisher()