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

org.bidib.jbidibc.net.serialovertcp.NetBidibPlainTcpPort Maven / Gradle / Ivy

The newest version!
package org.bidib.jbidibc.net.serialovertcp;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;

import org.bidib.jbidibc.messages.utils.ByteUtils;
import org.bidib.jbidibc.messages.utils.ThreadFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NetBidibPlainTcpPort implements NetBidibPort {
    private static final Logger LOGGER = LoggerFactory.getLogger(NetBidibPlainTcpPort.class);

    private final NetMessageHandler messageReceiver;

    private AtomicBoolean runEnabled = new AtomicBoolean();

    private Socket socket;

    private final ScheduledExecutorService acceptWorker;

    private String targetAddress;

    public NetBidibPlainTcpPort(InetAddress address, int portNumber, NetMessageHandler messageReceiver)
        throws IOException {
        if (address == null) {
            throw new IllegalArgumentException("address must not be null!");
        }

        this.messageReceiver = messageReceiver;
        this.targetAddress = address.toString() + ":" + portNumber;

        this.acceptWorker =
            Executors
                .newScheduledThreadPool(1,
                    new ThreadFactoryBuilder().setNameFormat("netBidibAcceptWorkers-thread-%d").build());

        // create the client socket
        this.socket = new Socket();
        this.socket.setTcpNoDelay(true);

        // connect timeout 10s
        this.socket.connect(new InetSocketAddress(address, portNumber), 10 * 1000);

        LOGGER.info("Created TCP socket for address: {},  port number: {}", address, portNumber);
    }

    @Override
    public void run() {
        LOGGER.info("Start the TCP socket.");
        runEnabled.set(true);

        LOGGER.info("Start client receiver handler.");
        // add a task to the worker to let the node process the send queue
        acceptWorker.submit(new NetBidibPlainTcpServerSocketHandler(socket, messageReceiver, null));
        LOGGER.info("Start client receiver handler has passed.");

        LOGGER.info("Start has passed.");
    }

    @Override
    public void stop() {
        LOGGER.info("Stop the TCP packet receiver, socket: {}", socket);
        runEnabled.set(false);

        if (socket != null) {
            try {
                socket.close();
            }
            catch (IOException ex) {
                LOGGER.warn("Close socket failed.", ex);
            }
            socket = null;
        }
    }

    private static final Logger MSG_RAW_LOGGER = LoggerFactory.getLogger("RAW");

    /**
     * Send the data to the host.
     * 
     * @param sendData
     *            the data to send
     * @param address
     *            the receiving address of the host
     * @param portNumber
     *            the receiving port number of the host
     * @throws IOException
     */
    @Override
    public void send(byte[] sendData, InetAddress address, int portNumber) throws IOException {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Send data to socket, port: {}, bytes: {}", portNumber, ByteUtils.bytesToHex(sendData));
        }

        if (MSG_RAW_LOGGER.isInfoEnabled()) {
            MSG_RAW_LOGGER.info(">> [{}] - {}", sendData.length, ByteUtils.bytesToHex(sendData));
        }

        socket.getOutputStream().write(sendData);
        socket.getOutputStream().flush();
    }

    @Override
    public String toString() {
        return "NetBidibPlainTcpPort[" + targetAddress + "]";
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy