Hi,
I want to write multithreaded UDP server and I found that there exist two approaches to implement it.I wonder what is the better approach and what are the pros and the cons of both.
First approach :
I have a main class that instantiates DatagramSocket and DatagramPacket, make a call to DatagramSocket.receive(DatagramPacket) in a loop and delegate to Runnable implementation, controlled by a ThreadPool.The Runnable implementation has a constructor with one parameter - DatagramPacket - and the implementation of run() use DatagramPacket.setData() of the supplied DatagramPacket to pack the response, then instantiates new DatagramSocket (without parameters) and use DatagramSocket.send() to send the response back (i.e. in each thread I instantiate a new DatagramSocket to send the response)
UDPServer.java
public static void main (final String[] args)
{
while(isRunning)
{
final byte[] buffer = new byte[BUFFER_SIZE];
final DatagramPacket receivedQuery = new DatagramPacket(buffer, buffer.length);
try
{
final DatagramSocket server = new DatagramSocket(PORT);
server.receive(receivedQuery);
final Worker worker = new UDPWorker(receivedQuery);
executor.execute(worker);
}
catches + termination issues ...
}
}
UDPWorker.java
public class UDPWorker implements Worker
{
private DatagramPacket packet = null;
public UDPWorker(final DatagramPacket aPacket)
{
packet = aPacket;
}
public void run()
{
packet.setData(getResponse());
DatagramSocket socket = null;
try
{
socket = new DatagramSocket();
socket.send(response);
socket.close();
}
catches + termination issues ...
}
}
Second approach :
In the main class I instantiate DatagramSocket, then instantiate given number of Runnable implementations, controlled by ThreadPool.The Runnable implementation has a constructor with one parameter - DatagramSocket - and is instantiated with the Socket-instance from the main class, then make call on DatagramSocket.receive() in a while-loop (i.e. for all the server-threads I have only one shared socket-instance) and send response again through the shared socket-instance (or alternate instantiate new socket for the response)
UDPServer.java
public static void main (final String[] args)
{
try
{
final DatagramSocket server = new DatagramSocket(PORT);
for(int i = 0; i < numberOfThreads; i++)
{
final Worker worker = new UDPWorker(server);
executor.execute(worker);
}
}
catches + termination issues ...
}
}
UDPWorker.java
public class UDPWorker implements Worker
{
private DatagramSocket server = null;
public UDPWorker(final DatagramSocket aServer)
{
server = aServer;
}
public void run()
{
while(isRunning)
{
final byte[] buffer = new byte[BUFFER_SIZE];
final DatagramPacket receivedQuery = new DatagramPacket(buffer, buffer.length);
try
{
server.receive(receivedQuery);
receivedQuery.setData(getResponse());
server.send(receivedQuery);
}
catches + termination issues ...
}
}
}
Could someone explain me what are the pros and the cons of both approaches respectively which is better?
Thanks in advance.