SpringBoot項目集成socketIo實現實時推送


 

  • netty-socketio maven依賴
<dependency>
      <groupId>com.corundumstudio.socketio</groupId>
      <artifactId>netty-socketio</artifactId>
      <version>1.7.7</version>
</dependency>

 

  • application.properties相關配置
#============================================================================
# netty socket io setting
#============================================================================
# host在本地測試可以設置為localhost或者本機IP,在Linux服務器跑可換成服務器IP
socketio.host=localhost
socketio.port=9099
# 設置最大每幀處理數據的長度,防止他人利用大數據來攻擊服務器
socketio.maxFramePayloadLength=1048576
# 設置http交互最大內容長度
socketio.maxHttpContentLength=1048576
# socket連接數大小(如只監聽一個端口boss線程組為1即可)
socketio.bossCount=1
socketio.workCount=100
socketio.allowCustomRequests=true
# 協議升級超時時間(毫秒),默認10秒。HTTP握手升級為ws協議超時時間
socketio.upgradeTimeout=1000000
# Ping消息超時時間(毫秒),默認60秒,這個時間間隔內沒有接收到心跳消息就會發送超時事件
socketio.pingTimeout=6000000
# Ping消息間隔(毫秒),默認25秒。客戶端向服務器發送一條心跳消息間隔
socketio.pingInterval=25000

 

  • SocketIOConfig.java配置文件相關配置
package com.vcgeek.hephaestus.socketio;

import com.corundumstudio.socketio.SocketConfig;
import com.corundumstudio.socketio.SocketIOServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 功能描述
 *
 * @author: zyu
 * @description:
 * @date: 2019/4/23 10:40
 */
@Configuration
public class SocketIOConfig {

    @Value("${socketio.host}")
    private String host;

    @Value("${socketio.port}")
    private Integer port;

    @Value("${socketio.bossCount}")
    private int bossCount;

    @Value("${socketio.workCount}")
    private int workCount;

    @Value("${socketio.allowCustomRequests}")
    private boolean allowCustomRequests;

    @Value("${socketio.upgradeTimeout}")
    private int upgradeTimeout;

    @Value("${socketio.pingTimeout}")
    private int pingTimeout;

    @Value("${socketio.pingInterval}")
    private int pingInterval;

    /**
     * 以下配置在上面的application.properties中已經注明
     * @return
     */
    @Bean
    public SocketIOServer socketIOServer() {
        SocketConfig socketConfig = new SocketConfig();
        socketConfig.setTcpNoDelay(true);
        socketConfig.setSoLinger(0);
        com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
        config.setSocketConfig(socketConfig);
        config.setHostname(host);
        config.setPort(port);
        config.setBossThreads(bossCount);
        config.setWorkerThreads(workCount);
        config.setAllowCustomRequests(allowCustomRequests);
        config.setUpgradeTimeout(upgradeTimeout);
        config.setPingTimeout(pingTimeout);
        config.setPingInterval(pingInterval);
        return new SocketIOServer(config);
    }

}

 

以下就是提供一個SocketIOService接口,供其他地方需要使用時調用。

package com.vcgeek.hephaestus.socketio;

import com.vcgeek.hephaestus.pojo.PushMessage;

/**
 * 功能描述
 *
 * @author: zyu
 * @description:
 * @date: 2019/4/23 10:41
 */
public interface SocketIOService {

    //推送的事件
    public static final String PUSH_EVENT = "push_event";

    // 啟動服務
    void start() throws Exception;

    // 停止服務
    void stop();

    // 推送信息
    void pushMessageToUser(PushMessage pushMessage);

}

 

  • SocketIOServiceImpl.java接口實現類
package com.vcgeek.hephaestus.socketio;

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.vcgeek.hephaestus.pojo.PushMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 功能描述
 *
 * @author: zyu
 * @description:
 * @date: 2019/4/23 10:42
 */
@Service(value = "socketIOService")
public class SocketIOServiceImpl implements SocketIOService {

    // 用來存已連接的客戶端
    private static Map<String, SocketIOClient> clientMap = new ConcurrentHashMap<>();

    @Autowired
    private SocketIOServer socketIOServer;

    /**
     * Spring IoC容器創建之后,在加載SocketIOServiceImpl Bean之后啟動
     *
     * @throws Exception
     */
    @PostConstruct
    private void autoStartup() throws Exception {
        start();
    }

    /**
     * Spring IoC容器在銷毀SocketIOServiceImpl Bean之前關閉,避免重啟項目服務端口占用問題
     *
     * @throws Exception
     */
    @PreDestroy
    private void autoStop() throws Exception {
        stop();
    }

    @Override
    public void start() throws Exception {
        // 監聽客戶端連接
        socketIOServer.addConnectListener(client -> {
            String loginUserNum = getParamsByClient(client);
            if (loginUserNum != null) {
                System.out.println(loginUserNum);
                System.out.println("SessionId:  " + client.getSessionId());
                System.out.println("RemoteAddress:  " + client.getRemoteAddress());
                System.out.println("Transport:  " + client.getTransport());
                clientMap.put(loginUserNum, client);
            }
        });

        // 監聽客戶端斷開連接
        socketIOServer.addDisconnectListener(client -> {
            String loginUserNum = getParamsByClient(client);
            if (loginUserNum != null) {
                clientMap.remove(loginUserNum);
                System.out.println("斷開連接: " + loginUserNum);
                System.out.println("斷開連接: " + client.getSessionId());
                client.disconnect();
            }
        });

        // 處理自定義的事件,與連接監聽類似
        socketIOServer.addEventListener("text", Object.class, (client, data, ackSender) -> {
            // TODO do something
            client.getHandshakeData();
            System.out.println( " 客戶端:************ " + data);

        });

        socketIOServer.start();
    }
    


    @Override
    public void stop() {
        if (socketIOServer != null) {
            socketIOServer.stop();
            socketIOServer = null;
        }
    }

    @Override
    public void pushMessageToUser(PushMessage pushMessage) {
        String loginUserNum = pushMessage.getLoginUserNum();
        if (StringUtils.isNotBlank(loginUserNum)) {
            SocketIOClient client = clientMap.get(loginUserNum);
            if (client != null)
                client.sendEvent(PUSH_EVENT, pushMessage);
        }
    }

    /**
     * 此方法為獲取client連接中的參數,可根據需求更改
     * @param client
     * @return
     */
    private String getParamsByClient(SocketIOClient client) {
        // 從請求的連接中拿出參數(這里的loginUserNum必須是唯一標識)
        Map<String, List<String>> params = client.getHandshakeData().getUrlParams();
        List<String> list = params.get("loginUserNum");
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    public static Map<String, SocketIOClient> getClientMap() {
        return clientMap;
    }

    public static void setClientMap(Map<String, SocketIOClient> clientMap) {
        SocketIOServiceImpl.clientMap = clientMap;
    }
}

 

  • 前端相關測試頁面編寫
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>NETTY SOCKET.IO DEMO</title>
    <base>
    <script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script>
    <style>
        body {
            padding: 20px;
        }
        #console {
            height: 450px;
            overflow: auto;
        }
        .username-msg {
            color: orange;
        }
        .connect-msg {
            color: green;
        }
        .disconnect-msg {
            color: red;
        }
    </style>
</head>

<body>
    <div id="console" class="well"></div>
    <button id="btnSend" onclick="send()">發送數據</button>
</body>
<script type="text/javascript">
    var socket;
    connect();

    function connect() {
        var loginUserNum = '79';
        var opts = {
            query: 'loginUserNum=' + loginUserNum
        };
        socket = io.connect('http://localhost:9099', opts);
        socket.on('connect', function () {
            console.log("連接成功");
            serverOutput('<span class="connect-msg">連接成功</span>');
        });
        socket.on('push_event', function (data) {
            output('<span class="username-msg">' + data + ' </span>');
            console.log(data);

        });

        socket.on('disconnect', function () {
            serverOutput('<span class="disconnect-msg">' + '已下線! </span>');
        });
    }
    
    function output(message) {
        var element = $("<div>" + " " + message + "</div>");
        $('#console').prepend(element);
    }

    function serverOutput(message) {
        var element = $("<div>" + message + "</div>");
        $('#console').prepend(element);
    }

    function send() {
        console.log('發送數據');
        socket.emit('text','你好');
    }


</script>
</html>

 

文章轉載:https://www.jianshu.com/p/c67853e729e2

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM