首页 > 解决方案 > 如何使用 springboot 和 reactjs 正确配置 websocket?

问题描述

@MessageMapping我可以与我的 springboot 服务器建立 websocket 连接,但是当我尝试发送消息时我无法访问端点。这是我的配置:

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/simulator")
            .setAllowedOrigins("http://myiphere:3000")
            .withSockJS();
}

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

还有一个简单的控制器:

@RestController
@RequestMapping("/api")
public class MyController {

 @MessageMapping("/hello/")
 @SendTo("/endpoint/greeting")
 public Greeting getCurrentLocation() {
     System.out.println("hello here");
     return GenericBuilder.of(Greeting::new)
                          .with(Greeting::setContent, "hello from server")
                          .build();
 }

}

我按照教程使用socketjs-clientReactJS 中的库:

import SockJS from "sockjs-client";
import Stomp from "stompjs";

let stompClient;

const connect = () => {
    const socket = new SockJS("http://myiphere:8081/simulator");
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        console.log("Connected " + frame);
        stompClient.subscribe("http://myiphere:8081/endpoint/greeting", function (greeting) {
        console.log("hi" + JSON.parse(greeting.body).content);
        });
    });
};

const sendSomething = () => {
    stompClient.send("http://myiphere:8081/app/hello/", {});
};

还有一些带有 onClick 事件的按钮绑定到上述方法。连接正常,我在浏览器控制台中收到“已连接”消息,但是当我尝试单击按钮时,sendSomething()在浏览器的控制台和服务器的控制台中都没有收到任何内容。

标签: reactjsspring-bootwebsocketspring-websocket

解决方案


解决了。

问题是方法中的绝对 url 路径send()

PS:我一直在许多网站上寻找这个问题的答案,发现没有必要对subscribe()url 使用绝对路径。

PPS:如果其他人有这些问题,也请寻找额外的/。设置网址时必须小心。来自 JS 的模式应该与来自 SpringBoot 的模式相匹配。


推荐阅读