WebSocket与Sockjs和Spring 4但没有Stomp

Blu*_*s23 33 java websocket sockjs spring-4

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

基于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);
            });
        });
Run Code Online (Sandbox Code Playgroud)

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

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

现在,据我所知,@MessageMapping("/hello")确保如果将消息发送到目标"/hello",则将greeting()调用该方法.并且由于stompClient订阅了"/topic/greetings",所以@SendTo("/topic/greetings")会将消息发送回stompClient.

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

sock.onmessage = function(e) {
     console.log('message', e.data);
 };
Run Code Online (Sandbox Code Playgroud)

那么,使用Spring 4,SockJS和没有Stomp的任何方法都可以做到这一点?或者Spring 4 WebSocket只支持Stomp?

Ser*_*mar 53

Spring支持STOMPWebSocket而是使用了子协议是不是强制的,你可以处理生的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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后将您的处理程序添加到配置中的注册表中(您可以添加多个处理程序并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();
    }
}
Run Code Online (Sandbox Code Playgroud)

客户端将是这样的:

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

sock.onmessage = function(e) {
    console.log('message', e.data);
}
Run Code Online (Sandbox Code Playgroud)

  • 当然,只需删除.withSockJS(); 从配置和使用普通的JS WebSocket API(你将没有任何后备选项) (3认同)
  • 这个答案很有效,但我现在想知道:在这个设置中是否可以向所有连接的客户端广播消息?在简单的JSR356 websockets中它很简单,所以我希望它在这里也可行. (2认同)
  • 如果没有.withSockJS() - >无法使用"ws:// localhost ...."进行连接,它对我不起作用,你能帮忙吗?我正在使用弹簧靴 (2认同)