Skip to content

Establish a TCP Client

Nikos Siatras edited this page Aug 18, 2024 · 10 revisions

The following class is a ready to to run TCP Client. For better understanding take a look at Extasys Examples

import Extasys.DataFrame;
import Extasys.DataConvertion.Base64Converter;
import Extasys.Network.TCP.Client.Connectors.TCPConnector;
import Extasys.Network.TCP.Client.Exceptions.ConnectorCannotSendPacketException;
import Extasys.Network.TCP.Client.Exceptions.ConnectorDisconnectedException;
import java.net.InetAddress;

/**
 *
 * @author Nikos Siatras
 */
public class TCPClient extends Extasys.Network.TCP.Client.ExtasysTCPClient
{

    private boolean fKeepSendingMessages = false;
    private final String fMessageToExchange = "128CharMessage111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111";
    private final char fMessageSplitter = (char) 3;

    public TCPClient(String name, String description, InetAddress remoteHostIP, int remoteHostPort, int corePoolSize, int maximumPoolSize)
    {
        super(name, description, corePoolSize, maximumPoolSize);

        try
        {
            TCPConnector connector = super.AddConnector(name, remoteHostIP, remoteHostPort, 8192, fMessageSplitter);
            connector.setAutoApplyMessageSplitterState(true); // Auto apply message splitter to outgoing messages
            connector.setConnectionDataConverter(new Base64Converter()); // Base 64 Encoding
        }
        catch (Exception ex)
        {
        }
    }

    @Override
    public void OnDataReceive(TCPConnector connector, DataFrame data)
    {
        try
        {
            //final String dataReceivedFromServer = new String(data.getBytes());

            // Every time I receive data from the server I send the
            // fMessageToExchange string back
            if (fKeepSendingMessages)
            {
                connector.SendData(fMessageToExchange)
            }
        }
        catch (ConnectorCannotSendPacketException | ConnectorDisconnectedException ex)
        {
            System.err.println(ex.getMessage());
        }
    }

    @Override
    public void OnConnect(TCPConnector connector)
    {
        System.out.println("Connected to server");
    }

    @Override
    public void OnDisconnect(TCPConnector connector)
    {
        System.out.println("Disconnected from server");
        StopSendingMessages();
    }

    public void StartSendingMessages()
    {
        fKeepSendingMessages = true;
        try
        {
            SendData(fMessageToExchange + fMessageSplitter);
        }
        catch (ConnectorDisconnectedException | ConnectorCannotSendPacketException ex)
        {
            fKeepSendingMessages = false;
        }
    }

    public void StopSendingMessages()
    {
        fKeepSendingMessages = false;
    }
}