JLChen
2021-11-09 c584c193d5dd4290bcbeddd434e1d642db59eb13
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.hdl.sdk.socket.client;
 
import android.net.Uri;
 
 
import androidx.collection.ArrayMap;
 
import java.net.DatagramSocket;
import java.net.Socket;
import java.net.SocketException;
 
/**
 * Created by Tong on 2021/10/8.
 */
public class ClientPool {
 
    private final ArrayMap<String, Socket> mTcpPool = new ArrayMap<>();
    private final ArrayMap<String, DatagramSocket> mUdpPool = new ArrayMap<>();
 
    private ClientPool() {
    }
 
    private static class SingletonInstance {
        private static final ClientPool INSTANCE = new ClientPool();
    }
 
    public static ClientPool getInstance() {
        return SingletonInstance.INSTANCE;
    }
 
    public Socket getTcpSocket(String ip, int port) {
        final StringBuilder key = new StringBuilder();
        key.append(ip).append(":").append(port);
        if (mTcpPool.containsKey(key)) {
            Socket socket = mTcpPool.get(key);
            if (socket != null && !socket.isClosed()) {
                return socket;
            }
 
        }
        return new Socket();
    }
 
    public DatagramSocket getUdpSocket(String ip, int port) throws SocketException {
        final StringBuilder key = new StringBuilder();
        key.append(ip).append(":").append(port);
        if (mUdpPool.containsKey(key)) {
            DatagramSocket socket = mUdpPool.get(key);
            if (socket != null && !socket.isClosed()) {
                return socket;
            }
 
        }
        return new DatagramSocket(port);
    }
 
}