最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

springboot?使用websocket技術(shù)主動給前端發(fā)送消息的實(shí)現(xiàn)

 更新時間:2021年12月20日 08:46:35   作者:yueF_L  
這篇文章主要介紹了springboot?使用websocket技術(shù)主動給前端發(fā)送消息的實(shí)現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

使用websocket技術(shù)主動給前端發(fā)送消息

springBoot2.0對WebSocket的支持簡直太棒了,直接就有包可以引入

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

WebSocketConfig

啟用WebSocket的支持也是很簡單

package com.spark.common.config; 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
 
/**
 * @Author Lxq
 * @Date 2021-06-12 17:11
 * @Version 1.0
 * 開啟websocket支持
 */
@Configuration
public class WebSocketConfig {
 
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
} 
 

WebSocketServer

這就是重點(diǎn)了,核心都在這里。

因?yàn)閃ebSocket是類似客戶端服務(wù)端的形式(采用ws協(xié)議),那么這里的WebSocketServer其實(shí)就相當(dāng)于一個ws協(xié)議的Controller

直接@ServerEndpoint("/socketServer/{userId}") 、@Component啟用即可,然后在里面實(shí)現(xiàn)@OnOpen開啟連接,@onClose關(guān)閉連接,@onMessage接收消息等方法。

新建一個ConcurrentHashMap webSocketMap 用于接收當(dāng)前userId的WebSocket,方便IM之間對userId進(jìn)行推送消息。單機(jī)版實(shí)現(xiàn)到這里就可以。

package com.spark.common.utils.websocket; 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.spark.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component; 
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
 
/**
 * @Author Lxq
 * @Date 2021-06-12 17:13
 * @Version 1.0
 */
@ServerEndpoint("/socketServer/{userId}")
@Component
@Slf4j
public class WebSocketServer { 
    /**
     * 靜態(tài)變量,用來記錄當(dāng)前在線連接數(shù)。應(yīng)該把它設(shè)計(jì)成線程安全的。
     */
    private static int onlineCount = 0;
    /**
     * concurrent包的線程安全Set,用來存放每個客戶端對應(yīng)的MyWebSocket對象。
     */
    private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**
     * 與某個客戶端的連接會話,需要通過它來給客戶端發(fā)送數(shù)據(jù)
     */
    private Session session;
    /**
     * 接收userId
     */
    private String userId = "";
 
    /**
     * 連接建立成功調(diào)用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            webSocketMap.put(userId, this);
            //加入set中
        } else {
            webSocketMap.put(userId, this);
            //加入set中
            addOnlineCount();
            //在線數(shù)加1
        }
 
        log.info("用戶連接:" + userId + ",當(dāng)前在線人數(shù)為:" + getOnlineCount());
 
        try {
            sendMessage("連接成功");
        } catch (IOException e) {
            log.error("用戶:" + userId + ",網(wǎng)絡(luò)異常!");
        }
    } 
 
    /**
     * 連接關(guān)閉調(diào)用的方法
     */
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            //從set中刪除
            subOnlineCount();
        }
        log.info("用戶退出:" + userId + ",當(dāng)前在線人數(shù)為:" + getOnlineCount());
    } 
 
    /**
     * 收到客戶端消息后調(diào)用的方法
     *
     * @param message 客戶端發(fā)送過來的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("用戶消息:" + userId + ",報文:" + message);
        //可以群發(fā)消息
        //消息保存到數(shù)據(jù)庫、redis
        if (StringUtils.isNotBlank(message)) {
            try {
                //解析發(fā)送的報文
                JSONObject jsonObject = JSON.parseObject(message);
                //追加發(fā)送人(防止串改)
                jsonObject.put("fromUserId", this.userId);
                String toUserId = jsonObject.getString("toUserId");
                //傳送給對應(yīng)toUserId用戶的websocket
                if (StringUtils.isNotBlank(toUserId) && webSocketMap.containsKey(toUserId)) {
                    webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
                } else {
                    log.error("請求的userId:" + toUserId + "不在該服務(wù)器上");
                    //否則不在這個服務(wù)器上,發(fā)送到mysql或者redis
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用戶錯誤:" + this.userId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }
 
    /**
     * 實(shí)現(xiàn)服務(wù)器主動推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    } 
 
    /**
     * 發(fā)送自定義消息
     */
    public static void sendInfo(String message, @PathParam("userId") String userId) throws IOException {
        log.info("發(fā)送消息到:" + userId + ",報文:" + message);
        if (StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)) {
            webSocketMap.get(userId).sendMessage(message);
        } else {
            log.error("用戶" + userId + ",不在線!");
        }
    }
 
    /**
     * 獲取當(dāng)前在線人數(shù)
     *
     * @return
     */
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }
 
    /**
     * 添加人數(shù)
     */
    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }
 
    /**
     * 減少人數(shù)
     */
    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    } 
}

websocket基礎(chǔ)入門-前端發(fā)送消息

項(xiàng)目結(jié)構(gòu)如下圖

33357527c7b06f63b0293469f03abc0c154.jpg

TestSocket.java

package com.charles.socket; 
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint; 
@ServerEndpoint(value = "/helloSocket")
public class TestSocket { 
    /***
     * 當(dāng)建立鏈接時,調(diào)用的方法.
     * @param session
     */
    @OnOpen
    public void open(Session session) {        
        System.out.println("開始建立了鏈接...");
        System.out.println("當(dāng)前session的id是:" + session.getId());
    }
    
    /***
     * 處理消息的方法.
     * @param session
     */
    @OnMessage
    public void message(Session session, String data) {        
        System.out.println("開始處理消息...");
        System.out.println("當(dāng)前session的id是:" + session.getId());
        System.out.println("從前端頁面?zhèn)鬟^來的數(shù)據(jù)是:" + data);
    }
}

index.jsp 代碼如下:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Charles-WebSocket</title> 
<script type="text/javascript">    
    var websocket = null;
    var target = "ws://localhost:8080/websocket/helloSocket";    
    function buildConnection() {
        
        if('WebSocket' in window) {
            websocket = new WebSocket(target);        
        } else if('MozWebSocket' in window) {
            websocket = MozWebSocket(target);
        } else {
            window.alert("瀏覽器不支持WebSocket");
        }
    }
    
    // 往后臺服務(wù)器發(fā)送消息.
    function sendMessage() {        
        var sendmsg = document.getElementById("sendMsg").value;
        console.log("發(fā)送的消息:" + sendmsg);        
        // 發(fā)送至后臺服務(wù)器中.
        websocket.send(sendmsg);
    }
    
</script>
</head>
<body>
    
    <button onclick="buildConnection();">開始建立鏈接</button>
    <hr>
    <input id="sendMsg" /> <button onclick="sendMessage();">消息發(fā)送</button> 
</body>
</html>

注意:

和后臺交互的時候,一定要先點(diǎn)擊:開始建立連接。你懂的...沒有建立連接的話,是不能發(fā)送消息的。

f2f6370a451a01a83682c64a37abe6e235d.jpg

先點(diǎn)擊,開始建立連接,然后在文本框中輸入內(nèi)容:我是Charles,點(diǎn)擊消息發(fā)送,在看后臺日志。

d83feaa70627b8e64a9d5026de88aca2f96.jpg

以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Mybatis使用連表查詢的操作代碼

    Mybatis使用連表查詢的操作代碼

    這篇文章主要介紹了Mybatis如何使用連表查詢,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-08-08
  • spring解決循環(huán)依賴的方案示例

    spring解決循環(huán)依賴的方案示例

    這篇文章主要介紹spring如何解決循環(huán)依賴,文中有相關(guān)的代碼示例給大家參考,對我們的學(xué)習(xí)或工作有一定的幫助,感興趣的同學(xué)可以借鑒閱讀
    2023-05-05
  • Java繼承的實(shí)現(xiàn)與繼承限制分析

    Java繼承的實(shí)現(xiàn)與繼承限制分析

    這篇文章主要介紹了Java繼承的實(shí)現(xiàn)與繼承限制,結(jié)合具體實(shí)例形式分析了Java繼承的定義、實(shí)現(xiàn)以及繼承的相關(guān)限制,需要的朋友可以參考下
    2019-01-01
  • Spring DI依賴注入實(shí)戰(zhàn)教程

    Spring DI依賴注入實(shí)戰(zhàn)教程

    這篇文章主要介紹了SpringDI依賴注入實(shí)戰(zhàn)教程,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2024-12-12
  • Java實(shí)現(xiàn)部門員工管理

    Java實(shí)現(xiàn)部門員工管理

    這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)部門員工管理,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-08-08
  • Spring中ClassPath指的是哪些地方

    Spring中ClassPath指的是哪些地方

    在Spring應(yīng)用中,ClassPath指的是應(yīng)用程序的類加載路徑,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-06-06
  • java如何實(shí)現(xiàn)樹形查詢

    java如何實(shí)現(xiàn)樹形查詢

    這篇文章主要介紹了java實(shí)現(xiàn)樹形查詢方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-07-07
  • 新手學(xué)習(xí)Java對Redis簡單操作

    新手學(xué)習(xí)Java對Redis簡單操作

    這篇文章主要介紹了新手學(xué)習(xí)Java對Redis簡單操作,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-04-04
  • SpringBoot搭建多數(shù)據(jù)源的實(shí)現(xiàn)方法

    SpringBoot搭建多數(shù)據(jù)源的實(shí)現(xiàn)方法

    說起多數(shù)據(jù)源,一般都來解決那些問題呢,主從模式或者業(yè)務(wù)比較復(fù)雜需要連接不同的分庫來支持業(yè)務(wù)。本文主要介紹了SpringBoot搭建多數(shù)據(jù)源的實(shí)現(xiàn)方法,感興趣的可以了解一下,感興趣的可以額了解一下
    2021-12-12
  • 使用@PathVariable接收兩個參數(shù)

    使用@PathVariable接收兩個參數(shù)

    這篇文章主要介紹了使用@PathVariable接收兩個參數(shù)的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08

最新評論

呼图壁县| 格尔木市| 洪雅县| 西乡县| 忻州市| 卓资县| 大丰市| 沅江市| 吴川市| 柳州市| 广元市| 保靖县| 镇远县| 新安县| 桂林市| 东辽县| 绩溪县| 常熟市| 承德县| 苍梧县| 方正县| 綦江县| 张家港市| 连云港市| 大理市| 米林县| 渑池县| 彝良县| 绩溪县| 平乐县| 达日县| 墨脱县| 江华| 奉节县| 精河县| 凤城市| 栾川县| 洪雅县| 汉沽区| 怀来县| 夏津县|