在每个HTTP请求上向客户端发送重脚消息

时间:2019-02-03 00:10:10

标签: java spring spring-boot websocket stomp

我有一个Spring Boot服务器和一个客户端,它们使用STOMP通过Websockets连接。

我的用例是,每次向特定端点发出http请求时,我都希望将数据发送到客户端。 我发现的所有教程都仅说明了这种情况,即客户端向“ / 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()) + "!");
}

我需要的是一种无需消息映射即可发送数据的控制器方法。每当有人向端点执行获取请求时,它就应该仅将数据发送到客户端。我尝试了以下操作,但没有成功:

@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";
}

这是我的客户代码:

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!!");
    });
}

这是我的WebSocket配置:

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

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/clipboard-websocket").withSockJS();
}

1 个答案:

答案 0 :(得分:1)

目标中缺少跟踪斜线

msgTemplate.convertAndSend("/topic/data-received", "data sent!!");

enter image description here

github-repo-issue-54498776