preface

Recently, a UDP data sending requirement is implemented. The front-end sends the request data to the server, and the server receives the data and sends it to other devices using UDP. When multiple requests are sent and the port is occupied before the previous request is sent, a port binding exception occurs when another request is sent.

Train of thought

  • Flow limiting control, allowing only one request to be sent at a time (not meeting business requirements)
  • User-defined port pool Manage port resources. You can obtain port resources from the port pool and put them back after using them

implementation

  • JavaSimple implementation
public class PortPool {

    // Save the port
    private static final Set<Integer> pool = new HashSet<>(526);

    private static volatile boolean init = false;

    public static Integer get(a) {
        Iterator<Integer> iterator = pool.iterator();
        if(pool.isEmpty() || ! iterator.hasNext()) {throw new RuntimeException("Port exhausted. Please try again later.");
        }
        Integer port = iterator.next();
        pool.remove(port);
        return port;
    }

    public static void recycle(Integer port) {
        if (port > 0&&! pool.contains(port)) { pool.add(port); }}// The port range can be specified from the configuration
    public static void init(Integer start, Integer end) {
        init = true;
        for (inti = start; i < end; i++) { pool.add(i); }}public static boolean hasInit(a) {
        returninit; }}Copy the code
  • Every timeUDPcreateSocketThe bound ports are obtained from the port pool
  • UDPRelease the port after sending data and put it back into the port pool

At the end

If this article is helpful to you, please like 👍🏻 to support it