Establish a TCP Server - nsiatras/extasys GitHub Wiki

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.Encryption.Base64Encryptor;
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);
            
            // Uncomment the following line to set Encryption for this TCP listener
            //fMyTCPListener.setConnectionEncryptor(new Base64Encryptor());
        }
        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);

            // Send the incoming data back to the client
            sender.SendData(incomingDataStr + fMessageSplitter);
        }
        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.");
    }
}