Stomp.py how to return message from listener

心已入冬 提交于 2019-11-30 18:45:52

问题


I've already read this topic: Stomp.py return message from listener

But i still don't get how this works, and why there's no way to retrieve a message from the stomp object, or the listener directly?

If i can send a message via the send method, and If i can receive a message with an on_message listener method, why can't I return that message to my original function, so I could return it to the frontend?

So if i have:

class MyListener(object):
    def on_error(self, headers, message):
        print '>>> ' + message
    def on_message(self, headers, message):
        print '>>> ' + message

how could I return a message from the on_message method?

or could I do it somehow after the conn.subscribe(...) ??


回答1:


Ok, I found a way myself. All you have to do, is a slight change of the listener class:

class MyListener(object):
    msg_list = []

    def __init__(self):
        self.msg_list = []

    def on_error(self, headers, message):
        self.msg_list.append('(ERROR) ' + message)

    def on_message(self, headers, message):
        self.msg_list.append(message)

And in the code, where u use stomp.py:

conn = stomp.Connection()
lst = MyListener()
conn.set_listener('', lst)
conn.start()
conn.connect()
conn.subscribe(destination='/queue/test', id=1, ack='auto')
time.sleep(2)
messages = lst.msg_list
conn.disconnect()
return render(request, 'template.html', {'messages': messages})


来源:https://stackoverflow.com/questions/23077284/stomp-py-how-to-return-message-from-listener

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