All Downloads are FREE. Search and download functionalities are using the official Maven repository.

shz.net.udp.DefaultUdpServerHandler Maven / Gradle / Ivy

There is a newer version: 10.1.1
Show newest version
package shz.net.udp;

import shz.core.ThreadHelp;
import shz.core.model.Request;
import shz.core.tuple.Tuple3;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.function.Consumer;

public abstract class DefaultUdpServerHandler extends UdpServerHandler {
    private final ExecutorService receiveExecutor;
    private final ExecutorService processingExecutor;
    private final boolean local;
    private final Map> requestPool;
    private final Map responsePool;

    protected DefaultUdpServerHandler(int port, ExecutorService receiveExecutor, ExecutorService processingExecutor, boolean local) {
        super(port);
        this.receiveExecutor = receiveExecutor == null
                ? ThreadHelp.getExecutor(ThreadHelp.TPConfig.of("UdpServerHandlerExecutor").tpType(ThreadHelp.TPType.FIXED_THREAD_POOL))
                : receiveExecutor;
        this.processingExecutor = processingExecutor == null ? this.receiveExecutor : processingExecutor;
        if (this.local = local) {
            requestPool = new ConcurrentHashMap<>();
            responsePool = new ConcurrentHashMap<>();
        } else {
            requestPool = null;
            responsePool = null;
        }
    }

    protected DefaultUdpServerHandler(int port, ExecutorService executor) {
        this(port, executor, null, true);
    }

    protected DefaultUdpServerHandler(int port) {
        this(port, null, null, true);
    }

    @Override
    protected final void asyncReceive(DatagramPacket packet, Consumer receive) {
        receiveExecutor.execute(() -> receive.accept(packet));
    }

    @Override
    protected final void asyncProcessing(Tuple3 tuple3, Consumer> processing) {
        processingExecutor.execute(() -> processing.accept(tuple3));
    }

    @Override
    public void saveIn(Request msg) {
        if (!local || msg == null) return;
        requestPool.put(msg.id(), msg);
    }

    @Override
    public Request getIn(ID id) {
        if (!local || id == null) return null;
        return requestPool.get(id);
    }

    @Override
    public void deleteIn(ID id) {
        if (!local || id == null) return;
        requestPool.remove(id);
    }

    @Override
    public void saveOut(ID id, Object msg) {
        if (!local || id == null) return;
        responsePool.put(id, msg);
    }

    @Override
    public Object getOut(ID id) {
        if (!local || id == null) return null;
        return responsePool.get(id);
    }

    @Override
    public void deleteOut(ID id) {
        if (!local || id == null) return;
        responsePool.remove(id);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy