[英]Sending stomp message to client on every http request
I have a spring boot server and a client which are connected via Websockets using STOMP. 我有一个弹簧启动服务器和一个客户端,它们使用STOMP通过Websockets连接。
My use case is that I want to send data to the client, every time a http request to a specific endpoint is made. 我的用例是每次向特定端点发出http请求时,我都希望将数据发送到客户端。 All the tutorials I found, only show the case, that the client sends some data to "/hello" and the server reacts by sending data to "topic/greetings":
我找到的所有教程,只显示案例,客户端将一些数据发送到“/ hello”,服务器通过向“topic / greetings”发送数据做出反应:
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
Thread.sleep(1000); // simulated delay
return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
}
What I need is a controller method that sends data without the need of the message mapping. 我需要的是一种无需消息映射即可发送数据的控制器方法。 It should just send data to the client every time someone performs a get request to the endpoint.
每当有人向端点执行get请求时,它应该只向客户端发送数据。 I tried the following, but it didn't work:
我尝试了以下,但它不起作用:
@Autowired
private SimpMessagingTemplate msgTemplate;
@SendTo("topic/data-received")
@RequestMapping(value = "/send-data", method = RequestMethod.POST)
public String sendData(@RequestHeader(value = "id") String id,
@RequestHeader(value = "data") String data) {
User user = new User();
user.id = UUID.fromString(id);
user.stringData = data;
database.saveStringData(user);
msgTemplate.convertAndSend("topic/data-received", "data sent!!");
return "successful";
}
Here is my client code: 这是我的客户端代码:
function connect() {
var socket = new SockJS('/clipboard-websocket');
var stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('topic/data-received/', function (message) {
alert("Data received!!");
});
}
And that's my WebSocket config: 那是我的WebSocket配置:
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/clipboard-websocket").withSockJS();
}
Trailing slash is missing in the destination 目标中缺少尾部斜杠
msgTemplate.convertAndSend("/topic/data-received", "data sent!!");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.