stomp-py

8.2.0 · active · verified Sat Apr 11

stomp.py is a Python client library for accessing messaging servers such as ActiveMQ, ActiveMQ Artemis, or RabbitMQ using the STOMP protocol (versions 1.0, 1.1, and 1.2). It provides both programmatic access and a command-line client for testing. The library, currently at version 8.2.0, adheres to semantic versioning and exclusively supports Python 3.x, having ended Python 2.x support in January 2020.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish a connection to a STOMP broker, register a listener to handle incoming messages, subscribe to a destination, send a message, and then disconnect. It uses environment variables for host, port, username, password, and destination, falling back to common defaults. It also explicitly sets STOMP protocol version 1.2 and heartbeats during connection.

import os
import time
import stomp

class MyListener(stomp.ConnectionListener):
    def on_error(self, headers, body):
        print(f'ERROR: {body}')

    def on_message(self, headers, body):
        print(f'MESSAGE: {body}')

host = os.environ.get('STOMP_HOST', 'localhost')
port = int(os.environ.get('STOMP_PORT', '61613'))
username = os.environ.get('STOMP_USERNAME', 'guest')
password = os.environ.get('STOMP_PASSWORD', 'guest')
destination = os.environ.get('STOMP_DESTINATION', '/queue/test')

host_and_ports = [(host, port)]

try:
    conn = stomp.Connection(host_and_ports)
    conn.set_listener(MyListener())
    conn.connect(username, password, wait=True, headers={'accept-version': '1.2', 'heart-beat': '10000,10000'})
    print(f"Connected to {host}:{port}")

    conn.subscribe(destination=destination, id=1, ack='auto')
    print(f"Subscribed to {destination}")

    print(f"Sending message to {destination}")
    conn.send(body='Hello, STOMP!', destination=destination)

    time.sleep(2) # Give time for message to be received

    conn.disconnect()
    print("Disconnected.")
except stomp.exception.ConnectFailedException as e:
    print(f"Failed to connect: {e}")
except Exception as e:
    print(f"An error occurred: {e}")

view raw JSON →