要在Spring Boot应用中集成和使用WebSocket,您需要遵循以下步骤:
pom.xml
文件中添加Spring Boot 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(new MyWebSocketHandler(), "/websocket")
.setAllowedOrigins("*");
}
}
public class MyWebSocketHandler extends TextWebSocketHandler {
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) {
// 处理收到的消息
}
}
@RestController
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.send('Hello, WebSocket!');
通过遵循以上步骤,您就可以在Spring Boot应用中成功集成和使用WebSocket。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。