Skip to content

Instantly share code, notes, and snippets.

@furqanbaqai
Forked from tdpreece/stomp_example.py
Created January 9, 2018 18:35
Show Gist options
  • Save furqanbaqai/50d0e9e46b618c32674842f628cb2dde to your computer and use it in GitHub Desktop.
Save furqanbaqai/50d0e9e46b618c32674842f628cb2dde to your computer and use it in GitHub Desktop.
stomp.py example
# Python 2.7.6
# stomp.py v4.1.5 (https://pypi.python.org/pypi/stomp.py)
import time
import stomp
class MyListener(stomp.ConnectionListener):
def on_message(self, headers, message):
print('MyListener:\nreceived a message "{}"\n'.format(message))
global read_messages
read_messages.append({'id': headers['message-id'], 'subscription':headers['subscription']})
class MyStatsListener(stomp.StatsListener):
def on_disconnected(self):
super(MyStatsListener, self).on_disconnected()
print('MyStatsListener:\n{}\n'.format(self))
read_messages = []
hosts = [('localhost', 21613)]
conn = stomp.Connection(host_and_ports=hosts)
conn.set_listener('my_listener', MyListener())
conn.set_listener('stats_listener', MyStatsListener())
conn.start()
# wait=True means that it waits until it's established a connection with the server before returning.
conn.connect(wait=True)
# id should uniquely identify the subscription
# ack = auto, client, or client-individual
# See https://stomp.github.io/stomp-specification-1.1.html#SUBSCRIBE_ack_Header
conn.subscribe(destination='test.req', id=1, ack='client-individual')
conn.send(body="A Test message", destination='test.req')
time.sleep(3)
for message in read_messages:
conn.ack(message['id'], message['subscription'])
conn.disconnect()
# Script output ...
#
# MyListener:
# received a message "A Test message"
#
# MyStatsListener:
# Connections: 1
# Messages sent: 5
# Messages received: 1
# Errors: 0
@jumbee126
Copy link

Hi, I tried your example with different versions (1.1 / 1.2 ) of the stomp library and i don't get same output as you. I always get 2 disconnections instead of 1 what is annoying. Can you explain this please ?
In my code i get same behaviour and would like to understand the root cause of this.
Many Thanks !

My output:

MyListener:
received a message "A Test message"

MyStatsListener:
Connections: 1
Disconnects: 1
Messages sent: 5
Messages received: 1
Heartbeats received: 0
Errors: 0

MyStatsListener:
Connections: 1
Disconnects: 2
Messages sent: 5
Messages received: 1
Heartbeats received: 0
Errors: 0

Process finished with exit code 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment