【发布时间】: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