SpringBoot開發(fā)私有即時(shí)通信系統(tǒng)(WebSocket)

1/ 概述

目前成都創(chuàng)新互聯(lián)公司已為上千家的企業(yè)提供了網(wǎng)站建設(shè)、域名、網(wǎng)頁空間、網(wǎng)站托管維護(hù)、企業(yè)網(wǎng)站設(shè)計(jì)、徐水網(wǎng)站維護(hù)等服務(wù),公司將堅(jiān)持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長,共同發(fā)展。

利用Spring Boot作為基礎(chǔ)框架,Spring Security作為安全框架,WebSocket作為通信框架,實(shí)現(xiàn)點(diǎn)對點(diǎn)聊天和群聊天。

2/ 所需依賴

Spring Boot 版本 1.5.3,使用MongoDB存儲數(shù)據(jù)(非必須),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數(shù)據(jù)庫 -->
 <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>

 <!-- 靜態(tài)資源 -->
 <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>

配置文件內(nèi)容:

server:
 port: 80

# 若使用MongoDB則配置如下參數(shù)
spring:
 data:
 mongodb:
  uri: mongodb://username:password@172.25.11.228:27017
  authentication-database: admin
  database: chat

大致程序結(jié)構(gòu),僅供參考:

Spring Boot 開發(fā)私有即時(shí)通信系統(tǒng)(WebSocket)

3/ 創(chuàng)建程序啟動類,啟用WebSocket

使用@EnableWebSocket注解

@SpringBootApplication
@EnableWebSocket
public class Application {

 public static void main(String[] args) {
 SpringApplication.run(Application.class, args);
 }

}

4/ 配置Spring Security

此章節(jié)省略。(配置好Spring Security,用戶能正常登錄即可)

5/ 配置Web Socket(結(jié)合第7節(jié)的JS看)

@Configuration
@EnableWebSocketMessageBroker
@Log4j
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

 // 此處可注入自己寫的Service

 @Override
 public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
 // 客戶端與服務(wù)器端建立連接的點(diǎn)
 stompEndpointRegistry.addEndpoint("/any-socket").withSockJS();
 }

 @Override
 public void configureMessageBroker(MessageBrokerRegistry messageBrokerRegistry) {
 // 配置客戶端發(fā)送信息的路徑的前綴
 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 {
   // 客戶端與服務(wù)器端建立連接后,此處記錄誰上線了
   String username = session.getPrincipal().getName();
   log.info("online: " + username);
   super.afterConnectionEstablished(session);
   }

   @Override
   public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
   // 客戶端與服務(wù)器端斷開連接后,此處記錄誰下線了
   String username = session.getPrincipal().getName();
   log.info("offline: " + username);
   super.afterConnectionClosed(session, closeStatus);
   }
  };
  }
 });
 super.configureWebSocketTransport(registration);
 }
}

6/ 點(diǎn)對點(diǎn)消息,群消息

@Controller
@Log4j
public class ChatController {

 @Autowired
 private SimpMessagingTemplate template;

 // 注入其它Service

 // 群聊天
 @MessageMapping("/notice")
 public void notice(Principal principal, String message) { 
 // 參數(shù)說明 principal 當(dāng)前登錄的用戶, message 客戶端發(fā)送過來的內(nèi)容
 // principal.getName() 可獲得當(dāng)前用戶的username 

 // 發(fā)送消息給訂閱 "/topic/notice" 且在線的用戶
 template.convertAndSend("/topic/notice", message); 
 }

 // 點(diǎn)對點(diǎn)聊天
 @MessageMapping("/chat")
 public void chat(Principal principal, String message){
 // 參數(shù)說明 principal 當(dāng)前登錄的用戶, message 客戶端發(fā)送過來的內(nèi)容(應(yīng)該至少包含發(fā)送對象toUser和消息內(nèi)容content)
 // principal.getName() 可獲得當(dāng)前用戶的username

 // 發(fā)送消息給訂閱 "/user/topic/chat" 且用戶名為toUser的用戶
 template.convertAndSendToUser(toUser, "/topic/chat", content);
 }

}

7/ 客戶端與服務(wù)器端交互

 var stompClient = null;

 function connect() {
  var socket = new SockJS('/any-socket');
  stompClient = Stomp.over(socket);
  stompClient.connect({}, function (frame) {
   // 訂閱 /topic/notice 實(shí)現(xiàn)群聊
   stompClient.subscribe('/topic/notice', function (message) {
    showMessage(JSON.parse(message.body));
   });
   // 訂閱 /user/topic/chat 實(shí)現(xiàn)點(diǎn)對點(diǎn)聊
   stompClient.subscribe('/user/topic/chat', function (message) {
    showMessage(JSON.parse(message.body));
   });
  });
 }

 function showMessage(message) {
  // 處理消息在頁面的顯示
 }

 $(function () {
  // 建立websocket連接
  connect();
  // 發(fā)送消息按鈕事件
  $("#send").click(function () {
   if (target == "TO_ALL"){
    // 群發(fā)消息
    // 匹配后端ChatController中的 @MessageMapping("/notice")
    stompClient.send("/app/notice", {}, '消息內(nèi)容');
   }else{
    // 點(diǎn)對點(diǎn)消息,消息中必須包含對方的username
    // 匹配后端ChatController中的 @MessageMapping("/chat")
    var content = "{'content':'消息內(nèi)容','receiver':'anoy'}";
    stompClient.send("/app/chat", {}, content);
   }
  });
 });

8/ 效果測試

登錄三個(gè)用戶:Anoyi、Jock、超級管理員。

群消息測試,超級管理員群發(fā)消息:Spring Boot 開發(fā)私有即時(shí)通信系統(tǒng)(WebSocket)

Spring Boot 開發(fā)私有即時(shí)通信系統(tǒng)(WebSocket)

Spring Boot 開發(fā)私有即時(shí)通信系統(tǒng)(WebSocket)

點(diǎn)對點(diǎn)消息測試,Anoyi給Jock發(fā)送消息,只有Jock收到消息,Anoyi和超級管理員收不到消息:

Spring Boot 開發(fā)私有即時(shí)通信系統(tǒng)(WebSocket)

Spring Boot 開發(fā)私有即時(shí)通信系統(tǒng)(WebSocket)

Spring Boot 開發(fā)私有即時(shí)通信系統(tǒng)(WebSocket)

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。

標(biāo)題名稱:SpringBoot開發(fā)私有即時(shí)通信系統(tǒng)(WebSocket)
分享網(wǎng)址:http://bm7419.com/article24/jdipce.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App設(shè)計(jì)、小程序開發(fā)、網(wǎng)站導(dǎo)航、移動網(wǎng)站建設(shè)、響應(yīng)式網(wǎng)站外貿(mào)網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都app開發(fā)公司