我有Python客户端,该客户端打开与服务器的Websocket连接并使用STOMP协议订阅特定主题,正如我在服务器上看到的那样,订阅进行得很好。但是,当服务器发布一些消息时,客户端不会收到任何消息。 以下是使用的代码:
客户
# coding: utf-8
import websocket
import stomp
import stomper
token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsInByaW5jaXBhbF9uYW1lIjoiYWRtaW4iLCJpc3MiOiJBdGhlbmEiLCJ1c2VydHlwZSI6IkxPQ0FMIiwiYW9zX3ZlcnNpb24iOiJldXBocmF0ZXMtNS4xMS1zdGFibGUiLCJyZWdpb24iOiJlbi1VUyIsImV4cCI6MTczNDI4MDI3NywidXVpZCI6ImI4MzhjOGRkLWI4NmQtNGNkZS05ZTE4LTUxM2E1OTk4ODhhYyIsImlhdCI6MTU3NjYwMDI3NywiYXV0aG9yaXRpZXMiOiJST0xFX0NMVVNURVJfQURNSU4sUk9MRV9NVUxUSUNMVVNURVJfQURNSU4sUk9MRV9VU0VSX0FETUlOLFJPTEVfQ0xVU1RFUl9WSUVXRVIiLCJqdGkiOiI1NTU1ZjEwZC04NGQ5LTRkZGYtOThhNC1mZmI1OTM1ZTQwZWEifQ.LOMX6ppkcSBBS_UwW9Qo2ieWZAGrKqADQL6ZQuTi2oieYa_LzykNiGMWMYXY-uw40bixDcE-aVWyrIEZQbVsvA"
headers = {"Authorization": "Bearer " + token}
uri = "ws://127.0.0.1:8765/notifications/websocket"
def on_msg(ws, msg):
print(msg)
def on_error(ws, err):
print(err)
def on_closed(ws):
print("#Closed#")
def on_open(ws):
sub = stomper.subscribe("/user/queue/alert", "MyuniqueId", ack="auto")
ws.send(sub)
headers = {"Authorization": "Bearer " + token}
websocket.enableTrace(True)
ws = websocket.WebSocketApp(uri, header=headers, on_message=on_msg, on_error=on_error, on_close=on_closed)
ws.on_open = on_open
ws.run_forever()
代码服务器用于发布消息:
for (WatchesSubscription s : subscriptions) {
template.convertAndSendToUser(s.getSession().getUser(), destination, dto);
}
当我检查出上述变量的值时,我看到目的地符合预期的 queue / alerts 。我也有java客户端可以测试,效果很好。我什至通过订阅/topic/alerts
并通过template.convertAndSend(/topic/alerts)
发送给我,在这里我也一无所获。我在此方面完全空白,将不胜感激!
答案 0 :(得分:3)
拉了好几天头发后,我终于弄清楚了原因和解决方法!
WebSocketStompClient stompClient = new WebSocketStompClient(transport);
。stompClient.connect(URL, webSocketHttpHeaders, sessionHandler);
方法隐式发送a脚CONNECT\n\n\x00\n
CONNECT_ACK
进行响应。UserRegistry
。因此内部邮件代理知道有一个用户订阅了某某主题。SUBSCRIBE
消息。因此,经纪人永远不会得到CONNECT
,因此永远不会存储用户!这导致稍后发布的消息仅由代理丢弃。CONNECT\n\n\x00\n
。这是代码:def on_open(ws):
#The magic happens here!
ws.send("CONNECT\naccept-version:1.0,1.1,2.0\n\n\x00\n")
sub = stomper.subscribe("/user/queue/alert", "MyuniqueId", ack="auto")
ws.send(sub)