sam*_*adi 5 spring spring-mvc spring-boot spring-websocket
Spring WebSocket的最新版本可与SockJS和StompJS库配合使用。但我不喜欢在我的应用程序中使用主题。那么如何使用HTML5 WebSocket API 创建 Spring WebSocket 应用程序 并将我们的应用程序与Spring Security集成?
我找不到任何关于如何在没有 sockjs 的情况下配置 spring websocket 的好例子,但我在 spring 文档网站中找到了一些有用的文档,我喜欢分享它。那么,如何使用 HTML5 WebSocket API 创建 Spring WebSocket 应用程序?
首先:创建一个扩展TextWebSocketHandler或BinaryWebSocketHandler 的类,并使用@Component注释对其进行注释并覆盖其适当的方法。该类的工作方式类似于控制器中的处理程序方法。
@Component
public class SimpleWebSocketHandler extends TextWebSocketHandler {
@Override
protected void handleTextMessage(WebSocketSession session,
TextMessage message) throws Exception {
// Sends back response to client.
session.sendMessage(new TextMessage("Connection is all right."));
}
}
Run Code Online (Sandbox Code Playgroud)
第二:创建一个实现 WebSocketConfigurer 的配置类,并使用@Configuration和@EnableWebSocket注释对其进行注释,并覆盖其适当的方法。该类使用我们已经创建的Handler类。
@Configuration
@EnableWebSocket
public class WebSocketConfigurations implements WebSocketConfigurer {
@Autowired
private SimpleWebSocketHandler simpleWebSocketHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
// Regsiters a handler for related endpoint.
registry.addHandler(simpleWebSocketHandler, "/chat");
}
}
Run Code Online (Sandbox Code Playgroud)
第三:将所有WebSokcet 端点添加到Spring Security Configuration中。
httpSecurity.authorizeRequests()
.antMatchers("/chat").permitAll();
Run Code Online (Sandbox Code Playgroud)
第四:我们使用适当的URL创建一个新的javascript WebSocket 对象。
// Create WebSocket Object.
var ws = new WebSocket("ws://localhost:8080/chat");
// Runs when connecion is estabilished.
ws.onopen = function () {
// Sends request to server with string value.
ws.send("webSocket");
};
// Runs when response is ready.
// Use event to get response value.
ws.onmessage = function (event) {
};
Run Code Online (Sandbox Code Playgroud)
注意:WebSocket URL 格式:ws://domain:port/endpoint
| 归档时间: |
|
| 查看次数: |
1246 次 |
| 最近记录: |