您好,登錄后才能下訂單哦!
要在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。