处理STOMP消息的Spring引导websockets

问题描述 投票:0回答:1

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

Web socket config.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");
    }
}

和消息控制器

message controller.Java

@Controller
public class MessageController {

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

还有我的javascript来处理websocket客户端

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#中的桌面应用程序。

java spring-boot stomp spring-websocket
1个回答
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();
}

如果您想使用@PathVariable,您应该映射发送消息:

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

并得到它定义映射,如:

@MessageMapping("/topic/{message}")
@SendTo("/topic/greetings")
public String handleMessage(@PathVariable String message){
© www.soinside.com 2019 - 2024. All rights reserved.