欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Springboot+WebSocket實(shí)現(xiàn)一對一聊天和公告的示例代碼

 更新時間:2021年04月26日 11:09:38   作者:一個頭發(fā)茂密的程序員  
這篇文章主要介紹了Springboot+WebSocket實(shí)現(xiàn)一對一聊天和公告的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

1.POM文件導(dǎo)入Springboot整合websocket的依賴

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <version>2.1.6.RELEASE</version>
        </dependency>

2.注冊WebSocket的Bean交給Spring容器管理

@Configuration
public class WebSocketServiceConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

3.WebSocket服務(wù)端實(shí)現(xiàn)

@ServerEndpoint 注解聲明為一個WebSocket服務(wù),訪問地址為/chat/{username},@Component將其注冊為Spring的一個組件,交給Spring進(jìn)行管理

@ServerEndpoint("/chat/{username}")
@Component
@Slf4j
public class WebSocket {
    //注入dao或者service,注意:因?yàn)閐ao層接口和service層都是單例的Bean
    //webSocket 不是單例的,所以在注入dao或者service時,需要用set方法對其進(jìn)行注入,保證每一個都是獨(dú)立的
     private static ChatMapper chatMapper;
      //參數(shù)中的ChatMapper  是 單例池中的ChatMapper 
    @Autowired
    public void setChatMapper(ChatMapper chatMapperBean){
        WebSocket.chatMapper = chatMapperBean;
    }

    //當(dāng)前連接數(shù)
    private static int onLinePersonNum;
    //定義為Map結(jié)構(gòu),key值代表用戶名稱或其他唯一標(biāo)識,Value代表對應(yīng)的WebSocket連接。
    //ConcurrentHashMap 保證線程安全,用來存放每個客戶端對應(yīng)的WebSocket對象
    private static Map<String,WebSocket> webSocketMap = new ConcurrentHashMap<String, WebSocket>();
   //用戶名
    private String username;
    //當(dāng)前httpSession
    private Session session;

    /**
     * 打開鏈接
     * @param username
     * @param session
     */
    @OnOpen
    public void openConnect(@PathParam("username")String username, Session session){
        this.session = session;
        this.username = username;
        //在線連接數(shù)+1
        onlinePerNumAdd();
        //用戶名和當(dāng)前用戶WebSocket對象放進(jìn)Map中
        webSocketMap.put(this.username,this);
        log.info("{}連接服務(wù)器成功。。。。",this.username);
    }

    /**
     * 關(guān)閉連接
     * @param username
     * @param session
     * @PathParam 用來獲取路徑中的動態(tài)參數(shù)Key值 
     */
    @OnClose
    public void closeConnect(@PathParam("username")String username, Session session){
        webSocketMap.remove(username);
        //在線連接數(shù)-1
        onlinePerNumSub();
        log.info("{} 斷開連接。。。",username);
    }

    /**
     * 錯誤提示
     */
    @OnError
    public void errorConnect(Session session, Throwable error){
        log.error("websocket連接異常:{}",error.getMessage());
    }

    @OnMessage
    public void send(String message, Session session) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        Map map = objectMapper.readValue(message, Map.class);
        sendMessage(map.get("username").toString(),message);
    }

    /**
     * 點(diǎn)對點(diǎn)發(fā)送
     * @param username
     * @param message
     * @throws IOException
     */
    private void sendMessage(String username,String message) throws IOException {
        WebSocket webSocket = webSocketMap.get(username);
        webSocket.session.getBasicRemote().sendText(message);
    }
     /**
     * 廣播類型發(fā)送
     * @param message
     * @throws IOException
     */
    private void sendMessage(String message) throws IOException {
        Set<String> keys = webSocketMap.keySet();
        for (String key : keys) {
            WebSocket webSocket = webSocketMap.get(key);
            webSocket.sendMessage(message);
        }
    }

    private synchronized static void onlinePerNumAdd(){
        WebSocket.onLinePersonNum ++;
    }
    private synchronized static void onlinePerNumSub(){
        WebSocket.onLinePersonNum --;
    }
    private synchronized static int getOnLinePerNum(){
        return WebSocket.onLinePersonNum;
    }
}

4.webSocket客戶端

chat1.html

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Title</title>
   <!--    <script src="https://heerey525.github.io/layui-v2.4.3/layui/layui.js"></script>-->
   <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
</head>
<body>
<!--<button id="user1" onclick="connect()">連接</button>-->
<input id="link" type="text"/>

<input id="sendMsg" type="text"/>
<button onclick="send()">發(fā)送</button>

<div id="message">

</div>
</body>

<script type="text/javascript">
   var websocket = null;
   // function connect() {
   //判斷當(dāng)前瀏覽器是否支持WebSocket  ,主要此處要更換為自己的地址
   if('WebSocket' in window){
       websocket = new WebSocket("ws://localhost:8089/chat/bbb");
   }
   else{
       alert('Not support websocket')
   }
   //連接發(fā)生錯誤的回調(diào)方法
   websocket.onerror = function(){
       // setMessageInnerHTML("error");
   };

   //連接成功建立的回調(diào)方法
   websocket.onopen = function(event){
       console.log("連接成功?。?!")
       // setMessageInnerHTML("open");
       $("#link").val("連接成功??!")
   }

   //連接關(guān)閉的回調(diào)方法
   websocket.onclose = function(){
       // setMessageInnerHTML("close");
   }

   //監(jiān)聽窗口關(guān)閉事件,當(dāng)窗口關(guān)閉時,主動去關(guān)閉websocket連接,防止連接還沒斷開就關(guān)閉窗口,server端會拋異常。
   window.onbeforeunload = function(){
       websocket.close();
   }
   //發(fā)送消息
   function send(){
       websocket.send("aaa");
       // onmessage();
   }

   //接收到消息的回調(diào)方法
   // function onmessage(){
   websocket.onmessage = function(event){
       console.log(event.data)
       // setMessageInnerHTML(event.data);
       $("#message").append("<h1>"+ event.data + "</h1>")
       // }
   }
</script>
</html>

chat2.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
<!--    <script src="https://heerey525.github.io/layui-v2.4.3/layui/layui.js"></script>-->
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
</head>
<body>
<!--<button id="user1" onclick="connect()">連接</button>-->
<input id="link" type="text"/>

<input id="sendMsg" type="text"/>
<button onclick="send()">發(fā)送</button>

<div id="message">

</div>
</body>

<script type="text/javascript">
    var websocket = null;
    // function connect() {
        //判斷當(dāng)前瀏覽器是否支持WebSocket  ,主要此處要更換為自己的地址
        if('WebSocket' in window){
            websocket = new WebSocket("ws://localhost:8089/pushMsg/aaa");
        }
        else{
            alert('Not support websocket')
        }
        //連接發(fā)生錯誤的回調(diào)方法
        websocket.onerror = function(){
            // setMessageInnerHTML("error");
        };

        //連接成功建立的回調(diào)方法
        websocket.onopen = function(event){
            console.log("連接成功?。?!")
            // setMessageInnerHTML("open");
            $("#link").val("服務(wù)器連接成功?。?)
        }

        //連接關(guān)閉的回調(diào)方法
        websocket.onclose = function(){
            // setMessageInnerHTML("close");
        }

        //監(jiān)聽窗口關(guān)閉事件,當(dāng)窗口關(guān)閉時,主動去關(guān)閉websocket連接,防止連接還沒斷開就關(guān)閉窗口,server端會拋異常。
        window.onbeforeunload = function(){
            websocket.close();
        }
    //發(fā)送消息
    function send(){
        websocket.send("bbb");
        // onmessage();
    }

    //接收到消息的回調(diào)方法
    // function onmessage(){
        websocket.onmessage = function(event){
            console.log(event.data)
            // setMessageInnerHTML(event.data);
            $("#message").append("<h1>"+ event.data + "</h1>")
        // }
    }

</script>
</html>

以上就是具體的代碼實(shí)現(xiàn),對于如果用戶離線,websocket斷開連接的情況,可以采用持久化的存儲方式。例如使用mysql關(guān)系型數(shù)據(jù)庫或Redis緩存等等保存用戶的讀取狀態(tài),當(dāng)用戶登錄后查詢用戶是否有未讀消息,然后進(jìn)行推送。

到此這篇關(guān)于Springboot+WebSocket實(shí)現(xiàn)一對一聊天和公告的示例代碼的文章就介紹到這了,更多相關(guān)Springboot WebSocket一對一聊天內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • springboot 多數(shù)據(jù)源的實(shí)現(xiàn)(最簡單的整合方式)

    springboot 多數(shù)據(jù)源的實(shí)現(xiàn)(最簡單的整合方式)

    這篇文章主要介紹了springboot 多數(shù)據(jù)源的實(shí)現(xiàn)(最簡單的整合方式),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11
  • Java核心教程之常見時間日期的處理方法

    Java核心教程之常見時間日期的處理方法

    這篇文章主要給大家介紹了關(guān)于Java核心教程之常見時間日期的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-02-02
  • JAVA+Struts2獲取服務(wù)器地址的方法

    JAVA+Struts2獲取服務(wù)器地址的方法

    這篇文章主要介紹了JAVA+Struts2獲取服務(wù)器地址的方法,是Struts2的一個簡單應(yīng)用,具有一定的借鑒與參考價(jià)值,需要的朋友可以參考下
    2014-11-11
  • Spring連接Mysql數(shù)據(jù)庫的實(shí)現(xiàn)步驟

    Spring連接Mysql數(shù)據(jù)庫的實(shí)現(xiàn)步驟

    本文主要介紹了Spring連接Mysql數(shù)據(jù)庫的實(shí)現(xiàn)步驟,文中根據(jù)實(shí)例編碼詳細(xì)介紹的十分詳盡,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • Struts 2中的constant配置詳解

    Struts 2中的constant配置詳解

    通過對這些屬性的配置,可以改變Struts 2 框架的一些默認(rèn)行為,這些配置可以在struts.xml文件中完成,也可以在struts.properties文件中完成
    2016-09-09
  • Springboot中動態(tài)語言groovy介紹

    Springboot中動態(tài)語言groovy介紹

    Apache的Groovy是Java平臺上設(shè)計(jì)的面向?qū)ο缶幊陶Z言,這門動態(tài)語言擁有類似Python、Ruby和Smalltalk中的一些特性,可以作為Java平臺的腳本語言使用,這篇文章主要介紹了springboot中如何使用groovy,需要的朋友可以參考下
    2022-09-09
  • Java實(shí)現(xiàn)在Word中嵌入多媒體(視頻、音頻)文件

    Java實(shí)現(xiàn)在Word中嵌入多媒體(視頻、音頻)文件

    這篇文章主要介紹了Java如何實(shí)現(xiàn)在Word中嵌入多媒體(視頻、音頻)文件,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)java有一定的幫助,感興趣的同學(xué)可以了解一下
    2021-12-12
  • java安全fastjson1.2.24反序列化TemplatesImpl分析

    java安全fastjson1.2.24反序列化TemplatesImpl分析

    這篇文章主要介紹了java安全fastjson1.2.24反序列化TemplatesImpl分析,fastjson是alibaba開源的一個用于處理json數(shù)據(jù)格式的解析庫,它支持將java對象解析成json字符串格式的數(shù)據(jù),也可以將json字符串還原成java對象
    2022-07-07
  • 利用POI讀取word、Excel文件的最佳實(shí)踐教程

    利用POI讀取word、Excel文件的最佳實(shí)踐教程

    Apache POI 是用Java編寫的免費(fèi)開源的跨平臺的 Java API,Apache POI提供API給Java程式對Microsoft Office格式檔案讀和寫的功能。 下面這篇文章主要給大家介紹了關(guān)于利用POI讀取word、Excel文件的最佳實(shí)踐的相關(guān)資料,需要的朋友可以參考下。
    2017-11-11
  • 關(guān)于任務(wù)調(diào)度框架quartz使用(異常處理,解決恢復(fù)后多次調(diào)度處理)

    關(guān)于任務(wù)調(diào)度框架quartz使用(異常處理,解決恢復(fù)后多次調(diào)度處理)

    這篇文章主要介紹了關(guān)于任務(wù)調(diào)度框架quartz使用(異常處理,解決恢復(fù)后多次調(diào)度處理),具有很好的參考價(jià)值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-12-12

最新評論