Java 带有 Sockjs 和 Spring 4 但没有 Stomp 的 WebSocket

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27158106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:55:25  来源:igfitidea点击:

WebSocket with Sockjs & Spring 4 but without Stomp

javawebsocketsockjsspring-4

提问by BlueChips23

Is there a way to use WebSockets with SockJS client and Spring 4 server but not using STOMP?

有没有办法将 WebSockets 与 SockJS 客户端和 Spring 4 服务器一起使用但不使用 STOMP?

Based on this tutorial from Spring's website, I know how to set up a WebSocket based application using Stomp and Spring 4. On the client side, we have:

根据 Spring 网站上的本教程,我知道如何使用 Stomp 和 Spring 4 设置基于 WebSocket 的应用程序。在客户端,我们有:

     var socket = new SockJS('/hello');
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function(frame) {
            setConnected(true);
            console.log('Connected: ' + frame);
            stompClient.subscribe('/topic/greetings', function(greeting){
                showGreeting(JSON.parse(greeting.body).content);
            });
        });

And on the server side, we have the following in the controller:

在服务器端,我们在控制器中有以下内容:

@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
    Thread.sleep(3000); // simulated delay
    return new Greeting("Hello, " + message.getName() + "!");
}

Now, I understand that @MessageMapping("/hello")ensures that if a message is sent to a destination "/hello", then the greeting()method will be called. And since the stompClientis subscribed to "/topic/greetings", the @SendTo("/topic/greetings")will send the message back to the stompClient.

现在,我明白@MessageMapping("/hello")确保如果将消息发送到目的地"/hello",则将greeting()调用该方法。并且由于stompClient订阅了"/topic/greetings"@SendTo("/topic/greetings")会将消息发送回stompClient

But the problem with the above is that stompClient is a Stomp object. And I want to simply use sock.send('test');and have it delivered to my server's destination. And I want to do @SendTo("myownclientdestinationmap"), I can receive it by

但是上面的问题是 stompClient 是一个 Stomp 对象。我想简单地使用sock.send('test');并将其交付到我的服务器目的地。我想做@SendTo("myownclientdestinationmap"),我可以通过

sock.onmessage = function(e) {
     console.log('message', e.data);
 };

So, any way to do this with Spring 4, SockJS and without Stomp? Or does Spring 4 WebSocket only supports Stomp?

那么,在没有 Stomp 的情况下,有什么方法可以使用 Spring 4、SockJS 来做到这一点?还是 Spring 4 WebSocket 只支持 Stomp?

采纳答案by Sergi Almar

Spring supports STOMPover WebSocketbut the use of a subprotocol is not mandatory, you can deal with the raw websocket. When using a raw websocket, the message sent lacks of information to make Spring route it to a specific message handler method (we don't have any messaging protocol), so instead of annotating your controller, you'll have to implement a WebSocketHandler:

Spring 支持STOMPoverWebSocket但子协议的使用不是强制性的,您可以处理原始 websocket。使用原始 websocket 时,发送的消息缺少信息,无法使 Spring 将其路由到特定的消息处理程序方法(我们没有任何消息传递协议),因此您不必注释控制器,而是必须实现WebSocketHandler

public class GreetingHandler extends TextWebSocketHandler {

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
        Thread.sleep(3000); // simulated delay
        TextMessage msg = new TextMessage("Hello, " + message.getPayload() + "!");
        session.sendMessage(msg);
    }
}

And then add your handler to the registry in the configuration (you can add more than one handler and use SockJSfor fallback options):

然后将您的处理程序添加到配置中的注册表(您可以添加多个处理程序并SockJS用于回退选项):

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(greetingHandler(), "/greeting").withSockJS();
    }

    @Bean
    public WebSocketHandler greetingHandler() {
        return new GreetingHandler();
    }
}

The client side will be something like this:

客户端将是这样的:

var sock = new SockJS('http://localhost:8080/greeting');

sock.onmessage = function(e) {
    console.log('message', e.data);
}