hxb
2023-06-28 531ba0d5bdc903c37e98128f04a85e0a146d23b7
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
package com.hdl.sdk.link.socket;
 
import com.hdl.sdk.link.socket.client.IClient;
 
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.concurrent.ConcurrentHashMap;
 
/**
 * Created by Tong on 2021/10/19.
 * 计划参考generic-pool、Commons Pool进行完善
 */
public class SocketPool {
 
    private final ConcurrentHashMap<String, IClient> mPool;
    private final ConcurrentHashMap<String, DatagramSocket> mUdpClientPool;
 
    private SocketPool() {
        mPool = new ConcurrentHashMap<>();
        mUdpClientPool = new ConcurrentHashMap<>();
    }
 
 
    private static class SingletonInstance {
        private static final SocketPool INSTANCE = new SocketPool();
    }
 
    public static SocketPool getInstance() {
        return SingletonInstance.INSTANCE;
    }
 
    public void clear() {
        mPool.clear();
        mUdpClientPool.clear();
    }
 
    public synchronized DatagramSocket getUdpSocket(InetSocketAddress address) throws SocketException {
        DatagramSocket socket = null;
        final String key = address.getPort() + "";
        if (mUdpClientPool.containsKey(key)) {
            socket = mUdpClientPool.get(key);
            if (socket != null && socket.isClosed()) {
                mUdpClientPool.remove(key);
                socket = null;
            }
        }
        if (socket == null) {
            socket = new DatagramSocket(address);
            mUdpClientPool.put(key, socket);
        }
        return socket;
    }
}