wjc
2024-12-23 f753d8366041354da60b8096060f3ab5159e3880
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
package com.hdl.sdk.link.socket;
 
import com.hdl.sdk.link.socket.client.IClient;
 
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
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, MulticastSocket> 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 MulticastSocket getUdpSocket(InetSocketAddress address) throws IOException {
        MulticastSocket 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 MulticastSocket(address);
            mUdpClientPool.put(key, socket);
        }
        return socket;
    }
}