简体   繁体   中英

Spring boot server and python client using Websocket

I'm using a stack of 2 applications, one with back-office which ask a database and so one, and hosting a websocket server (Java / Spring Boot + React)

The second application is a Python app which need to be notified when an action is in progress on back-office.

So the best solution on my side is websocket, but I'm facing a problem when try to connect on the websocket server using Python.

Here is my code

SpringServer configuration

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

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

Sring handler

@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 client

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)

But I got an error Handshake status 200 OK , maybe there is a mistake on my server side configuration. (I try using withSockJS() and without this parameter, it doesn't change anything)

Anyone can help me on this topic?

Thanks a lot !

I'm still working on this issue, but without can't find a solution to my issue.

I find a part of the solution, which is closest use case that I can do: Python client doesn't receive messages from Spring websocket server (without any answer)

@sampie777 did you find a solution?

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

Have you tried to add /websocket to the endpoint? It fixed the same issue in my case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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