New file |
| | |
| | | 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;
|
| | | }
|
| | | }
|