利用Spring Boot做爲基礎框架,Spring Security做爲安全框架,WebSocket做爲通訊框架,實現點對點聊天和羣聊天。html
Spring Boot 版本 1.5.3,使用MongoDB存儲數據(非必須),Maven依賴以下:java
<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>
配置文件內容:jquery
server: port: 80 # 若使用MongoDB則配置以下參數 spring: data: mongodb: uri: mongodb://username:password@172.25.11.228:27017 authentication-database: admin database: chat
大體程序結構,僅供參考:git
使用@EnableWebSocket
註解github
@SpringBootApplication @EnableWebSocket public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
此章節省略。(配置好Spring Security,用戶能正常登陸便可)
能夠參考:Spring Boot 全棧開發:用戶安全web
@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); } }
@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); } }
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); } }); });
登陸三個用戶:Anoyi、Jock、超級管理員。
羣消息測試,超級管理員羣發消息:spring
點對點消息測試,Anoyi給Jock發送消息,只有Jock收到消息,Anoyi和超級管理員收不到消息:mongodb
Spring Boot 開發私有即時通訊系統(WebSocket)(續)數據庫
更多資料: 2020 年 精選阿里 Java、架構、微服務精選等,加 v ❤ :gongchengshi6678json
本文由博客一文多發平臺 OpenWrite 發佈!