-
Notifications
You must be signed in to change notification settings - Fork 16
Establish a UDP Client
Nikos Siatras edited this page Aug 18, 2024
·
8 revisions
The following class is a ready to run UDP Client. For better understanding take a look at Extasys Examples
import Extasys.DataConvertion.Base64Converter;
import Extasys.Network.UDP.Client.Connectors.UDPConnector;
import java.net.DatagramPacket;
import java.net.InetAddress;
/**
*
* @author Nikos Siatras
*/
public class UDPClient extends Extasys.Network.UDP.Client.ExtasysUDPClient
{
private AutoSendMessages fAutoSendMessagesThread;
public UDPClient(String name, String description, int readTimeOut, int corePoolSize, int maximumPoolSize, InetAddress remoteHostIP, int remoteHostPort)
{
super(name, description, corePoolSize, maximumPoolSize);
// Add a UDP connector to this UDP client.
// You can add more than one connectors if you need to.
UDPConnector conn = super.AddConnector("My connector", 10240, 10000, remoteHostIP, remoteHostPort);
conn.setConnectionEncryptor(new Base64Encryptor()); // Base64 Encoding
}
@Override
public void OnDataReceive(UDPConnector connector, DatagramPacket packet)
{
System.out.println("Data received: " + new String(packet.getData()));
}
public void StartSendingMessages()
{
StopSendingMessages();
fAutoSendMessagesThread = new AutoSendMessages(this);
fAutoSendMessagesThread.start();
}
public void StopSendingMessages()
{
if (fAutoSendMessagesThread != null)
{
fAutoSendMessagesThread.Dispose();
fAutoSendMessagesThread.interrupt();
}
}
}
class AutoSendMessages extends Thread
{
private final UDPClient fMyClient;
private boolean fActive = true;
public AutoSendMessages(UDPClient client)
{
fMyClient = client;
}
@Override
public void run()
{
int messageCount = 0;
while (fActive)
{
try
{
messageCount++;
String msgToSend = String.valueOf(messageCount);
fMyClient.SendData(msgToSend.getBytes());
Thread.sleep(300);
}
catch (Exception ex)
{
Dispose();
fMyClient.StopSendingMessages();
}
}
}
public void Dispose()
{
fActive = false;
}
}