webSocket介绍与使用 spring boot 集成 websocket教程 java
在Spring Boot中集成WebSocket可以通过Spring WebSocket支持来完成。以下是一个简单的例子:
- 添加依赖到你的
pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
- 配置WebSocket,创建一个配置类:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
}
- 创建一个控制器来处理WebSocket请求:
@Controller
public class WebSocketController {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) {
return new Greeting("Hello, " + message.getName() + "!");
}
}
class Greeting {
private String content;
// getters and setters
}
class HelloMessage {
private String name;
// getters and setters
}
- 在前端使用WebSocket:
var socket = new SockJS('/ws');
var stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', function(greeting){
console.log(JSON.parse(greeting.body).content);
});
});
stompClient.send("/app/hello", {}, JSON.stringify({ 'name': 'John Doe' }));
以上代码展示了如何在Spring Boot应用中设置WebSocket服务器,并定义了一个简单的消息映射。客户端使用SockJS和Stomp.js与服务器进行通信。
评论已关闭