Netty-SocketIO+scoket-io-client實現實時聊天思路


一、后端

參考https://www.jianshu.com/p/c67853e729e2

1、引入依賴

<dependency>
    <groupId>com.corundumstudio.socketio</groupId>
    <artifactId>netty-socketio</artifactId>
    <version>1.7.7</version>
</dependency>

2、application.properties相關配置

# 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

3、SocketIOConfig.java配置文件相關配置

 1 import com.corundumstudio.socketio.SocketConfig;
 2 import org.springframework.beans.factory.annotation.Value;
 3 import org.springframework.context.annotation.Bean;
 4 import org.springframework.context.annotation.Configuration;
 5 
 6 import com.corundumstudio.socketio.SocketIOServer;
 7 
 8 @Configuration
 9 public class SocketIOConfig {
10 
11     @Value("${socketio.host}")
12     private String host;
13 
14     @Value("${socketio.port}")
15     private Integer port;
16 
17     @Value("${socketio.bossCount}")
18     private int bossCount;
19 
20     @Value("${socketio.workCount}")
21     private int workCount;
22 
23     @Value("${socketio.allowCustomRequests}")
24     private boolean allowCustomRequests;
25 
26     @Value("${socketio.upgradeTimeout}")
27     private int upgradeTimeout;
28 
29     @Value("${socketio.pingTimeout}")
30     private int pingTimeout;
31 
32     @Value("${socketio.pingInterval}")
33     private int pingInterval;
34 
35     /**
36      * 以下配置在上面的application.properties中已經注明
37      * @return
38      */
39     @Bean
40     public SocketIOServer socketIOServer() {
41         SocketConfig socketConfig = new SocketConfig();
42         socketConfig.setTcpNoDelay(true);
43         socketConfig.setSoLinger(0);
44         com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
45         config.setSocketConfig(socketConfig);
46         config.setHostname(host);
47         config.setPort(port);
48         config.setBossThreads(bossCount);
49         config.setWorkerThreads(workCount);
50         config.setAllowCustomRequests(allowCustomRequests);
51         config.setUpgradeTimeout(upgradeTimeout);
52         config.setPingTimeout(pingTimeout);
53         config.setPingInterval(pingInterval);
54         return new SocketIOServer(config);
55     }
56 }

四、提供SocketIOService接口

public interface SocketIOService {
// 啟動服務
    void start() throws Exception;
    
    // 停止服務
    void stop();
    
}

五、具體實現方法

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;

@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() {
        // 監聽客戶端連接
        socketIOServer.addConnectListener(client -> {
            String loginUserNum = getParamsByClient(client);
            if (loginUserNum != null) {
                clientMap.put(loginUserNum, client);
            }
        });

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

        // 處理自定義的事件,與連接監聽類似,event為事件名,PushMessage為參數實體類
     // 監聽前端發送的事件
socketIOServer.addEventListener("event", PushMessage.class, (client, data, ackSender) -> { // TODO do something }); socketIOServer.start(); } @Override public void stop() { if (socketIOServer != null) { socketIOServer.stop(); socketIOServer = null; } } public void pushMessageToUser(PushMessage pushMessage) { String loginUserNum = pushMessage.getLoginUserNum(); if (StringUtils.isNotBlank(loginUserNum)) { SocketIOClient client = clientMap.get(loginUserNum); if (client != null)
         // 通過sendEvent給前端發送事件,並傳遞參數 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; } }

 

二、前端

1、下載

npm install socket.io-client

2、引入

import io from 'socket.io-client';

3、監聽連接、自定義事件、退出

mounted {
  // 連接參數
  let opts = new Object();
  // 連接scoket服務器,ip為socket地址
  var socket = io('ip', opts);
  // 監聽連接后的回調
  socket.on('connect', function(){});
  // 監聽自定義事件,event為事件名,並接受后台傳過來的參數    
  socket.on('event', function(data){});
  // 監聽退出后的回調函數
  socket.on('disconnect', function(){});
}

4、發送事件

// event為事件名,data為參數
socket.emit('event', data);

 

三、總結

1、前端可以通過socket.on來監聽,socket.emit來發送事件。

2、后端可以通過SocketIOClient的sendEvent發送事件,socketIOServer.addDisconnectListener來監聽。


免責聲明!

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



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