-
-
Save furqanbaqai/50d0e9e46b618c32674842f628cb2dde to your computer and use it in GitHub Desktop.
stomp.py example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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