Skip to content

Establish a UDP Server

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

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

import Extasys.DataConvertion.Base64Converter;
import Extasys.Network.UDP.Server.Listener.UDPListener;
import java.net.DatagramPacket;
import java.net.InetAddress;

/**
 *
 * @author Nikos Siatras
 */
public class UDPServer extends Extasys.Network.UDP.Server.ExtasysUDPServer
{

    public UDPServer(String name, String description, InetAddress listenerIP, int port, int connectionsTimeOut, int corePoolSize, int maximumPoolSize)
    {
        super(name, description, corePoolSize, maximumPoolSize);
        UDPListener listener = this.AddListener("My UDP Listener", listenerIP, port, 10240, connectionsTimeOut);
        listener.setConnectionDataConverter(new Base64Converter()); // Base64 Encoding
    }

    @Override
    public void OnDataReceive(UDPListener listener, DatagramPacket packet)
    {
        System.out.println("Data received from " + packet.getAddress().toString() + ": " + new String(packet.getData()));

        try
        {
            // Send data back to the sender.
            listener.SendData(new DatagramPacket(packet.getData(), 0, packet.getLength(), packet.getAddress(), packet.getPort()));
        }
        catch (Exception ex)
        {
        }
    }
}