【问题标题】:How to properly configure websocket with springboot and reactjs?如何使用 springboot 和 reactjs 正确配置 websocket?
【发布时间】:2020-09-17 14:56:09
【问题描述】:

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

@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();
 }

}

我按照this 教程在 ReactJS 中使用socketjs-client 库:

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() 的按钮时,我在浏览器控制台和服务器控制台中都没有收到任何内容。

【问题讨论】:

    标签: reactjs spring-boot websocket spring-websocket


    【解决方案1】:

    解决了。

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

    P.S.:我一直在许多网站上寻找这个问题的答案,发现不需要为subscribe() url 使用绝对路径。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-17
      • 2022-08-14
      • 1970-01-01
      • 2014-12-28
      • 2020-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多