在后台接入Spring WebSocket请求,可以按照以下步骤进行:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myWebSocketHandler(), "/websocket")
.setAllowedOrigins("*");
}
@Bean
public WebSocketHandler myWebSocketHandler() {
return new MyWebSocketHandler();
}
}
public class MyWebSocketHandler implements WebSocketHandler {
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// 连接建立后的处理逻辑
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
// 处理接收到的消息
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
// 错误处理逻辑
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
// 连接关闭后的处理逻辑
}
@Override
public boolean supportsPartialMessages() {
return false;
}
}
@Controller
public class WebSocketController {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public String greeting(String message) {
return "Hello, " + message + "!";
}
}
var socket = new WebSocket('ws://localhost:8080/websocket');
socket.onopen = function() {
console.log('WebSocket连接已建立');
};
socket.onmessage = function(event) {
console.log('接收到消息:' + event.data);
};
socket.onclose = function() {
console.log('WebSocket连接已关闭');
};
socket.send('Hello, Server!');
以上是在后台接入Spring WebSocket请求的基本步骤。根据具体需求,你可以进一步扩展和定制WebSocket的功能,例如添加身份验证、消息广播等。
领取专属 10元无门槛券
手把手带您无忧上云