Skip to content

Establish a TCP Server

Nikos Siatras edited this page Aug 29, 2024 · 25 revisions

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

import Extasys.DataFrame;
import Extasys.DataConvertion.Base64Converter;
import Extasys.Network.TCP.Server.Listener.Exceptions.ClientIsDisconnectedException;
import Extasys.Network.TCP.Server.Listener.Exceptions.OutgoingPacketFailedException;
import Extasys.Network.TCP.Server.Listener.TCPClientConnection;
import Extasys.Network.TCP.Server.Listener.TCPListener;
import java.net.InetAddress;

/**
 *
 * @author Nikos Siatras
 */
public class TCPServer extends Extasys.Network.TCP.Server.ExtasysTCPServer
{

    private TCPListener fMyTCPListener;
    private final char fMessageSplitter = (char) 3;
   
    public TCPServer(String name, String description, InetAddress listenerIP, int port, int maxConnections, int connectionsTimeOut, int corePoolSize, int maximumPoolSize)
    {
        super(name, description, corePoolSize, maximumPoolSize);

        try
        {
            // Add a listener with message collector.
            fMyTCPListener = this.AddListener("My listener", listenerIP, port, maxConnections, 8192, connectionsTimeOut, 100,  fMessageSplitter);
            fMyTCPListener.setAutoApplyMessageSplitterState(true);  // Auto apply message splitter to outgoing messages
            fMyTCPListener.setConnectionDataConverter(new Base64Converter()); // Base 64 Encoding
        }
        catch (Exception ex)
        {
        }
    }

    @Override
    public void OnDataReceive(TCPClientConnection sender, DataFrame data)
    {
        try
        {
            // I received data from a client
            final String incomingDataStr = new String(data.getBytes());
            System.out.println("Data received: " + incomingDataStr);

            sender.SendData(incomingDataStr);
        }
        catch (ClientIsDisconnectedException | OutgoingPacketFailedException ex)
        {

        }
    }

    @Override
    public void OnClientConnect(TCPClientConnection client)
    {
        // New client connected.
        client.setName(client.getIPAddress()); // Set a name for this client if you want to.
        System.out.println(client.getIPAddress() + " connected.");
        System.out.println("Total clients connected: " + super.getCurrentConnectionsNumber());
    }

    @Override
    public void OnClientDisconnect(TCPClientConnection client)
    {
        // Client disconnected.
        System.out.println(client.getIPAddress() + " disconnected.");
    }
}