Spring Boot 開發私有即時通信系統(WebSocket)。本站提示廣大學習愛好者:(Spring Boot 開發私有即時通信系統(WebSocket))文章只能為提供參考,不一定能成為您想要的結果。以下是Spring Boot 開發私有即時通信系統(WebSocket)正文
1/ 概述
利用Spring Boot作為基礎框架,Spring Security作為安全框架,WebSocket作為通信框架,實現點對點聊天和群聊天。
2/ 所需依賴
Spring Boot 版本 1.5.3,使用MongoDB存儲數據(非必須),Maven依賴如下:
<properties> <java.version>1.8</java.version> <thymeleaf.version>3.0.0.RELEASE</thymeleaf.version> <thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version> </properties> <dependencies> <!-- WebSocket依賴,移除Tomcat容器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <!-- 使用Undertow容器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-undertow</artifactId> </dependency> <!-- Spring Security 框架 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- MongoDB數據庫 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <!-- Thymeleaf 模版引擎 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.16</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.30</version> </dependency> <!-- 靜態資源 --> <dependency> <groupId>org.webjars</groupId> <artifactId>webjars-locator</artifactId> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>sockjs-client</artifactId> <version>1.0.2</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>stomp-websocket</artifactId> <version>2.3.3</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>3.3.7</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.1.0</version> </dependency> </dependencies>
配置文件內容:
server: port: 80 # 若使用MongoDB則配置如下參數 spring: data: mongodb: uri: mongodb://username:[email protected]:27017 authentication-database: admin database: chat
大致程序結構,僅供參考:
3/ 創建程序啟動類,啟用WebSocket
使用@EnableWebSocket
注解
@SpringBootApplication @EnableWebSocket public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
4/ 配置Spring Security
此章節省略。(配置好Spring Security,用戶能正常登錄即可)
5/ 配置Web Socket(結合第7節的JS看)
@Configuration @EnableWebSocketMessageBroker @Log4j public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { // 此處可注入自己寫的Service @Override public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) { // 客戶端與服務器端建立連接的點 stompEndpointRegistry.addEndpoint("/any-socket").withSockJS(); } @Override public void configureMessageBroker(MessageBrokerRegistry messageBrokerRegistry) { // 配置客戶端發送信息的路徑的前綴 messageBrokerRegistry.setApplicationDestinationPrefixes("/app"); messageBrokerRegistry.enableSimpleBroker("/topic"); } @Override public void configureWebSocketTransport(final WebSocketTransportRegistration registration) { registration.addDecoratorFactory(new WebSocketHandlerDecoratorFactory() { @Override public WebSocketHandler decorate(final WebSocketHandler handler) { return new WebSocketHandlerDecorator(handler) { @Override public void afterConnectionEstablished(final WebSocketSession session) throws Exception { // 客戶端與服務器端建立連接後,此處記錄誰上線了 String username = session.getPrincipal().getName(); log.info("online: " + username); super.afterConnectionEstablished(session); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { // 客戶端與服務器端斷開連接後,此處記錄誰下線了 String username = session.getPrincipal().getName(); log.info("offline: " + username); super.afterConnectionClosed(session, closeStatus); } }; } }); super.configureWebSocketTransport(registration); } }
6/ 點對點消息,群消息
@Controller @Log4j public class ChatController { @Autowired private SimpMessagingTemplate template; // 注入其它Service // 群聊天 @MessageMapping("/notice") public void notice(Principal principal, String message) { // 參數說明 principal 當前登錄的用戶, message 客戶端發送過來的內容 // principal.getName() 可獲得當前用戶的username // 發送消息給訂閱 "/topic/notice" 且在線的用戶 template.convertAndSend("/topic/notice", message); } // 點對點聊天 @MessageMapping("/chat") public void chat(Principal principal, String message){ // 參數說明 principal 當前登錄的用戶, message 客戶端發送過來的內容(應該至少包含發送對象toUser和消息內容content) // principal.getName() 可獲得當前用戶的username // 發送消息給訂閱 "/user/topic/chat" 且用戶名為toUser的用戶 template.convertAndSendToUser(toUser, "/topic/chat", content); } }
7/ 客戶端與服務器端交互
var stompClient = null; function connect() { var socket = new SockJS('/any-socket'); stompClient = Stomp.over(socket); stompClient.connect({}, function (frame) { // 訂閱 /topic/notice 實現群聊 stompClient.subscribe('/topic/notice', function (message) { showMessage(JSON.parse(message.body)); }); // 訂閱 /user/topic/chat 實現點對點聊 stompClient.subscribe('/user/topic/chat', function (message) { showMessage(JSON.parse(message.body)); }); }); } function showMessage(message) { // 處理消息在頁面的顯示 } $(function () { // 建立websocket連接 connect(); // 發送消息按鈕事件 $("#send").click(function () { if (target == "TO_ALL"){ // 群發消息 // 匹配後端ChatController中的 @MessageMapping("/notice") stompClient.send("/app/notice", {}, '消息內容'); }else{ // 點對點消息,消息中必須包含對方的username // 匹配後端ChatController中的 @MessageMapping("/chat") var content = "{'content':'消息內容','receiver':'anoy'}"; stompClient.send("/app/chat", {}, content); } }); });
8/ 效果測試
登錄三個用戶:Anoyi、Jock、超級管理員。
群消息測試,超級管理員群發消息:
點對點消息測試,Anoyi給Jock發送消息,只有Jock收到消息,Anoyi和超級管理員收不到消息:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。