【Springboot系列】SpringBoot整合WebSocket,既然如此简单(含源码)
以下是一个使用Spring Boot整合WebSocket的简单示例。
首先,添加依赖到你的pom.xml
文件:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
然后,配置WebSocket:
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");
registry.setApplicationDestinationPrefixes("/app");
}
}
接下来,创建一个控制器来处理WebSocket消息:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class WebSocketController {
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public String greeting(String message) {
return "Hello, " + message + "!";
}
@RequestMapping("/sendMessage")
@ResponseBody
public String sendMessage(String message) {
simpMessagingTemplate.convertAndSend("/topic/greetings", "Hello, " + message + "!");
return "Message sent";
}
}
最后,在HTML页面中使用WebSocket:
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Test</title>
<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1.7.0/dist/sockjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/s
评论已关闭