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支持STOMP了WebSocket而是使用了子协议是不是强制的,你可以处理生的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)
| 归档时间: |
|
| 查看次数: |
20594 次 |
| 最近记录: |