Spring Boot WebSockets处理STOMP消息

时间:2018-06-29 12:41:01

标签: java spring-boot stomp spring-websocket

我有一个Spring Boot WebSocket服务器,这是我的代理配置

WebSocketConfig.java

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

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

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

和消息控制器

MessageController.java

@Controller
public class MessageController {

    @MessageMapping("/topic")
    @SendTo("/topic/greetings/{message}")
    public String handleMessage(@PathVariable String message){
        return "[" + message + "] at " + LocalDate.now();
    }
}

也是我用来处理websocket客户端的JavaScript

app.js

var stompClient = null;

function connect() {
    var socket = new SockJS('/endpoint');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        setConnected(true);
        console.log('Connected: ' + frame);
        stompClient.subscribe('/topic/greetings/asd', function (message){
            console.log("Message received: " + message)
        });
    });
}

function setConnected(connected) {
    $("#connect").prop("disabled", connected);
    $("#disconnect").prop("disabled", !connected);
    $("#greetings").html("");
}

function disconnect() {
    if (stompClient !== null) {
        stompClient.disconnect();
    }
    setConnected(false);
    console.log("Disconnected");
}

function sendName() {
    stompClient.send("/app/topic", {}, $("#name").val());
}

$(function () {
    $("form").on('submit', function (e) {
        e.preventDefault();
    });
    $( "#connect" ).click(function() { connect(); });
    $( "#disconnect" ).click(function() { disconnect(); });
    $( "#send" ).click(function() { sendName(); });
});

和html页面

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Hello WebSocket</title>
    <link href="/webjars/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="/main.css" rel="stylesheet">
    <script src="/webjars/jquery/jquery.min.js"></script>
    <script src="/webjars/sockjs-client/sockjs.min.js"></script>
    <script src="/webjars/stomp-websocket/stomp.min.js"></script>
    <script src="/app.js"></script>
</head>
<body>
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websocket relies on Javascript being
    enabled. Please enable
    Javascript and reload this page!</h2></noscript>
<div id="main-content" class="container">
    <div class="row">
        <div class="col-md-6">
            <form class="form-inline">
                <div class="form-group">
                    <label for="connect">WebSocket connection:</label>
                    <button id="connect" class="btn btn-default" type="submit">Connect</button>
                    <button id="disconnect" class="btn btn-default" type="submit" disabled="disabled">Disconnect
                    </button>
                </div>
            </form>
        </div>
        <div class="col-md-6">
            <form class="form-inline">
                <div class="form-group">
                    <label for="name">What is your name?</label>
                    <input type="text" id="name" class="form-control" placeholder="Your name here...">
                </div>
                <button id="send" class="btn btn-default" type="submit">Send</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>

因此,应将/app/topic处收到的每条消息都发送到/topic/gretings/{message},但不是。我有一个错误:

java.lang.IllegalArgumentException: Could not resolve placeholder 'message' in value "/topic/greetings/{message}"

我读过其他文章,人们使用的是@DestinationVariable而不是@PathVariable,但是我还有其他错误:

org.springframework.messaging.MessageHandlingException: Missing path template variable 'message' for method parameter type [class java.lang.String]

关键是客户端订阅自己的频道并与其他客户端交换数据,其他客户端将是C#中的桌面应用程序。

1 个答案:

答案 0 :(得分:0)

当您使用stompClient.send("/app/topic", {}, $("#name").val());在正文中发送邮件时,应使用@RequestBody而不是@PathVariable

要获取已发布消息的内容:

@MessageMapping("/topic")
public String handleMessage(@RequestBody String message){

接下来可以在充实到主题/topic/greetings之后发送:

@SendTo("/topic/greetings")

将所有内容放在一起将获得来自/app/topic的消息并发送给/topic/greetings的订户

@MessageMapping("/topic")
@SendTo("/topic/greetings")
public String handleMessage(@RequestBody String message){
    return "[" + message + "] at " + LocalDate.now();
}