[英]SockJS Python Client
我有一個網站(Java + Spring),它的某些功能依賴於 Websockets( Stomp over Websockets for Spring + RabbitMQ + SockJS)。
我們正在創建一個基於 Python 的命令行界面,我們希望添加一些使用 websockets 已經可用的功能。
有誰知道如何使用 python 客戶端,以便我可以使用 SockJS 協議進行連接?
PS_我知道一個簡單的庫,我沒有測試過,但它沒有訂閱主題的能力
PS2_ 因為我可以從 python直接連接到RabbitMQ上的STOMP並訂閱主題,但直接公開 RabbitMQ 感覺不對。 關於第二個選項的任何評論?
我使用的解決方案是不使用 SockJS 協議,而是使用“普通的網絡套接字”並使用 Python 中的 websockets 包並使用 stomper 包通過它發送 Stomp 消息。 stomper 包只生成作為“消息”的字符串,您只需使用ws.send(message)
通過 websockets 發送這些消息
服務器上的 Spring Websockets 配置:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/my-ws-app"); // Note we aren't doing .withSockJS() here
}
}
在代碼的 Python 客戶端:
import stomper
from websocket import create_connection
ws = create_connection("ws://theservername/my-ws-app")
v = str(random.randint(0, 1000))
sub = stomper.subscribe("/something-to-subscribe-to", v, ack='auto')
ws.send(sub)
while not True:
d = ws.recv()
m = MSG(d)
現在d
將是一個 Stomp 格式的消息,它具有非常簡單的格式。 MSG 是我寫的一個快速而骯臟的類來解析它。
class MSG(object):
def __init__(self, msg):
self.msg = msg
sp = self.msg.split("\n")
self.destination = sp[1].split(":")[1]
self.content = sp[2].split(":")[1]
self.subs = sp[3].split(":")[1]
self.id = sp[4].split(":")[1]
self.len = sp[5].split(":")[1]
# sp[6] is just a \n
self.message = ''.join(sp[7:])[0:-1] # take the last part of the message minus the last character which is \00
這不是最完整的解決方案。 沒有取消訂閱,Stomp 訂閱的 id 是隨機生成的,不會“記住”。 但是,stomper 庫為您提供了創建取消訂閱消息的能力。
服務器端發送到/something-to-subscribe-to
都將被訂閱它的所有 Python 客戶端接收。
@Controller
public class SomeController {
@Autowired
private SimpMessagingTemplate template;
@Scheduled(fixedDelayString = "1000")
public void blastToClientsHostReport(){
template.convertAndSend("/something-to-subscribe-to", "hello world");
}
}
}
我已經回答了從 Springboot 服務器通過 websockets 回退到 Python 客戶端的 Springboot 服務器發送 STOMP 消息的特定問題: Websocket 客戶端沒有收到任何消息。 它還解決了上述評論
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.