亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

springboot websocket簡單入門示例

 更新時間:2018年08月15日 10:04:49   作者:王強勁  
這篇文章主要介紹了springboot websocket簡單入門示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

之前做的需求都是客戶端請求服務(wù)器響應(yīng),新需求是服務(wù)器主動推送信息到客戶端.百度之后有流、長輪詢、websoket等方式進行.但是目前更加推崇且合理的顯然是websocket.

從springboot官網(wǎng)翻譯了一些資料,再加上百度簡單實現(xiàn)了springboot使用websocekt與客戶端的雙工通信.

1.首先搭建一個簡單的springboot環(huán)境

<!-- Inherit defaults from Spring Boot -->
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.4.RELEASE</version>
  </parent>

  <!-- Add typical dependencies for a web application -->
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
  </dependencies>

2.引入springboot整合websocket依賴

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-websocket -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-websocket</artifactId>
  <version>2.0.4.RELEASE</version>
</dependency>

3.創(chuàng)建啟動springboot的核心類

package com;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

4.創(chuàng)建websocket服務(wù)器

正如springboot 官網(wǎng)推薦的websocket案例,需要實現(xiàn)WebSocketHandler或者繼承TextWebSocketHandler/BinaryWebSocketHandler當中的任意一個.

package com.xiaoer.handler;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * 相當于controller的處理器
 */
public class MyHandler extends TextWebSocketHandler {
  @Override
  protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    String payload = message.getPayload();
    Map<String, String> map = JSONObject.parseObject(payload, HashMap.class);
    System.out.println("=====接受到的數(shù)據(jù)"+map);
    session.sendMessage(new TextMessage("服務(wù)器返回收到的信息," + payload));
  }
}

5.注冊處理器

package com.xiaoer.config;

import com.xiaoer.handler.MyHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
  @Override
  public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    registry.addHandler(myHandler(), "myHandler/{ID}");
  }
  public WebSocketHandler myHandler() {
    return new MyHandler();
  }

}

6.運行訪問


出現(xiàn)如上圖是因為不能直接通過http協(xié)議訪問,需要通過html5的ws://協(xié)議進行訪問.

7.創(chuàng)建Html5 客戶端

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title></title>
  </head>
  <body>
    <input id="text" type="text" />
    <button onclick="send()">Send</button>  
    <button onclick="closeWebSocket()">Close</button>
    <div id="message">
    </div>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script>
      
      var userID="888";
      var websocket=null;

      $(function(){
        connectWebSocket();
      })
      
      //建立WebSocket連接
      function connectWebSocket(){

        console.log("開始...");
       
       //建立webSocket連接
        websocket = new WebSocket("ws://127.0.0.1:8080/myHandler/ID="+userID);
       
       //打開webSokcet連接時,回調(diào)該函數(shù)
        websocket.onopen = function () {   
          console.log("onpen"); 
        }
        
        //關(guān)閉webSocket連接時,回調(diào)該函數(shù)
        websocket.onclose = function () {
        //關(guān)閉連接  
          console.log("onclose");
        }

        //接收信息
        websocket.onmessage = function (msg) {
          console.log(msg.data);
        }

      }
      //發(fā)送消息
      function send(){
        var postValue={};
        postValue.id=userID;
        postValue.message=$("#text").val();     
        websocket.send(JSON.stringify(postValue));
      }
      //關(guān)閉連接
      function closeWebSocket(){
        if(websocket != null) {
          websocket.close();
        }
      }
    </script>
  </body>
</html>

8.運行


利用客戶端運行之后仍然會出現(xiàn)上圖中的一連接就中斷了websocket連接.

這是因為spring默認不接受跨域訪問:

As of Spring Framework 4.1.5, the default behavior for WebSocket and SockJS is to accept only same origin requests.

需要在WebSocketConfig中設(shè)置setAllowedOrigins.

package com.xiaoer.config;

import com.xiaoer.handler.MyHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
  @Override
  public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    registry.addHandler(myHandler(), "myHandler/{ID}")
      .setAllowedOrigins("*");
  }
  public WebSocketHandler myHandler() {
    return new MyHandler();
  }

}

如下圖,并未輸出中斷,說明連接成功.

9.服務(wù)器和客戶端的相互通信

服務(wù)器端收到消息


客戶端收到服務(wù)器主動推送消息

以上就是一個最基礎(chǔ)的springboot簡單應(yīng)用.還可以通過攔截器、重寫WebSocketConfigurer中的方法進行更為復(fù)雜的屬性操作.具體可以參考SpringBoot集成WebSocket【基于純H5】進行點對點[一對一]和廣播[一對多]實時推送

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • SpringBoot請求參數(shù)相關(guān)注解說明小結(jié)

    SpringBoot請求參數(shù)相關(guān)注解說明小結(jié)

    這篇文章主要介紹了SpringBoot請求參數(shù)相關(guān)注解說明,主要包括@PathVariable,@RequestHeader、@CookieValue、@RequestBody和@RequestParam,本文結(jié)合實例代碼給大家講解的非常詳細,需要的朋友可以參考下
    2022-05-05
  • Java線程中的ThreadLocal類解讀

    Java線程中的ThreadLocal類解讀

    這篇文章主要介紹了Java線程中的ThreadLocal類解讀,ThreadLocal是一個泛型類,作用是實現(xiàn)線程隔離,ThreadLocal類型的變量,在每個線程中都會對應(yīng)一個具體對象,對象類型需要在聲明ThreadLocal變量時指定,需要的朋友可以參考下
    2023-11-11
  • Spring Boot Actuator監(jiān)控的簡單使用方法示例代碼詳解

    Spring Boot Actuator監(jiān)控的簡單使用方法示例代碼詳解

    這篇文章主要介紹了Spring Boot Actuator監(jiān)控的簡單使用,本文通過實例代碼圖文相結(jié)合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-06-06
  • nexus私服啟動不了問題及解決

    nexus私服啟動不了問題及解決

    這篇文章主要介紹了nexus私服啟動不了問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-04-04
  • JDK12的新特性之teeing collectors

    JDK12的新特性之teeing collectors

    這篇文章主要介紹了JDK12的新特性之teeing collectors的相關(guān)資料,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-05-05
  • SpringBoot基于Sentinel在服務(wù)上實現(xiàn)接口限流

    SpringBoot基于Sentinel在服務(wù)上實現(xiàn)接口限流

    這篇文章主要介紹了SpringBoot基于Sentinel在服務(wù)上實現(xiàn)接口限流,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-10-10
  • Hibernate中的多表查詢及抓取策略

    Hibernate中的多表查詢及抓取策略

    本文主要介紹了Hibernate中的多表查詢及抓取策略,具有很好的參考價值,下面跟著小編一起來看下吧
    2017-02-02
  • 詳解Spring獲取配置的三種方式

    詳解Spring獲取配置的三種方式

    這篇文章主要為大家詳細介紹了Spring獲取配置的三種方式:@Value方式動態(tài)獲取單個配置、@ConfigurationProperties+前綴方式批量獲取配置以及Environment動態(tài)獲取單個配置,感興趣的可以了解一下
    2022-03-03
  • Spring中七種事務(wù)傳播機制詳解

    Spring中七種事務(wù)傳播機制詳解

    這篇文章主要介紹了Spring中七種事務(wù)傳播機制詳解,Spring在TransactionDefinition接口中規(guī)定了7種類型的事務(wù)傳播行為,Propagation枚舉則引用了這些類型,開發(fā)過程中我們一般直接用Propagation枚舉,需要的朋友可以參考下
    2024-01-01
  • java實現(xiàn)角色及菜單權(quán)限的項目實踐

    java實現(xiàn)角色及菜單權(quán)限的項目實踐

    在Java中,實現(xiàn)角色及菜單權(quán)限管理涉及定義實體類、設(shè)計數(shù)據(jù)庫表、實現(xiàn)服務(wù)層和控制器層,這種管理方式有助于有效控制用戶權(quán)限,適用于企業(yè)級應(yīng)用,感興趣的可以一起來了解一下
    2024-09-09

最新評論