繁体   English   中英

Spring 引导服务器和 python 客户端使用 Websocket

[英]Spring boot server and python client using Websocket

我正在使用一组 2 个应用程序,一个带有后台询问数据库等一个,并托管 websocket 服务器(Java / Spring Boot + React)

第二个应用程序是 Python 应用程序,当后台执行操作时需要通知该应用程序。

所以我这边最好的解决方案是 websocket,但是当我尝试使用 Python 在 websocket 服务器上连接时遇到问题。

这是我的代码

SpringServer 配置

@Override
public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
    stompEndpointRegistry.addEndpoint("/ws").setAllowedOrigins("*");
}

@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.enableSimpleBroker("/topic", "/queue");
    registry.setApplicationDestinationPrefixes("/app");
}

字符串处理程序

@Scheduled(fixedDelayString = "1000")
public void blastToClientsHostReport() {
    log.debug("Sending something on the websocket");
    messagingTemplate.convertAndSend("/topic/greeting", "Hello World");
}

@MessageMapping("/greeting")
public String handle(String message) {
    log.debug("Received message: $message");
    messagingTemplate.convertAndSend("/topic/greeting", message);
    String tm = DateTimeFormatter.ISO_INSTANT.format(Instant.now());
    return "[" + tm + ": " + message + "]";
}

Python客户端

websocket.enableTrace(True)

# Connecting to websocket
ws = websocket.create_connection("ws://localhost:8080/ws")

# Subscribing to topic
client_id = str(random.randint(0, 1000))
sub = stomper.subscribe("/topic/greeting", client_id, ack='auto')
ws.send(sub)

# Sending some message
ws.send(stomper.send("/app/greeting", "Hello there"))

while True:
    print("Receiving data: ")
    d = ws.recv()
    print(d)

但是我收到错误Handshake status 200 OK ,可能是我的服务器端配置有误。 (我尝试使用 withSockJS() 并且没有这个参数,它不会改变任何东西)

任何人都可以在这个话题上帮助我吗?

非常感谢 !

我仍在研究这个问题,但找不到解决我的问题的方法。

我找到了解决方案的一部分,这是我可以做的最接近的用例: Python client doesn't receive messages from Spring websocket server (without any answer)

@sampie777 你找到解决方案了吗?

ws = websocket.create_connection("ws://localhost:8080/ws/websocket")

您是否尝试将 /websocket 添加到端点? 在我的情况下,它解决了同样的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM