I believe there is some problem in this code. First of all, is this the
right way to write it? Second, I know that the client only send short
requests to the server, while the server sends much more data back. Will the
server be sending more than one packet? How can I write the code so that
"Keep listening for multiple packet from the server and send them to the
client"?
Many thank.
Patrick.
public static void run()
{
int bufferLength = 512;
// Packets received from and sent to the client
DatagramPacket clientSendPacket, clientReceivePacket;
// Packets sent to and received from the server
DatagramPacket serverSendPacket, serverReceivePacket;
// Socket facing the client
DatagramSocket listenSocket = null;
// Socket facing the server
DatagramSocket forwardSocket = null;
byte buf[] = null;
while (true)
{
try
{
buf = new byte[bufferLength];
clientReceivePacket = new DatagramPacket(buf,bufferLength);
// Listen for client request
listenSocket = new DatagramSocket(this.port);
listenSocket.setSoTimeout(100);
listenSocket.receive(clientReceivePacket);
frame.appendOutputText("Received from client "
+ clientReceivePacket.getAddress().toString()
+ ", port "
+ clientReceivePacket.getPort()
+ ".\nLength "
+ clientReceivePacket.getLength() + "\n");
listenSocket.close();
// Send the packet to the server
frame.appendOutputText("Construct forward packet.\n");
serverSendPacket = new DatagramPacket(
buf,
clientReceivePacket.getLength(),
InetAddress.getByName("192.168.0.2"),
this.port);
frame.appendOutputText("Open socket.\n");
forwardSocket = new DatagramSocket();
frame.appendOutputText("Forward client packet.\n");
forwardSocket.send(serverSendPacket);
// Listen for server reply
buf = new byte[bufferLength];
serverReceivePacket = new DatagramPacket(buf,bufferLength);
forwardSocket.setSoTimeout(100);
forwardSocket.receive(serverReceivePacket);
frame.appendOutputText("Received from server "
+ serverReceivePacket.getAddress().toString()
+ ", port "
+ serverReceivePacket.getPort()
+ ".\nLength "
+ serverReceivePacket.getLength() + "\n");
// forwardSocket.close();
// Send packet back to client
frame.appendOutputText("Return client packet.\n");
clientSendPacket = new DatagramPacket(
buf,
serverReceivePacket.getLength(),
clientReceivePacket.getAddress(),
clientReceivePacket.getPort()
);
listenSocket = new DatagramSocket(this.port);
listenSocket.send(clientSendPacket);
maxcount++;
}
catch (InterruptedIOException iioe)
{
// Thrown when time out
}
catch (Exception e)
{
frame.appendOutputText("Exception: " + e.toString() + "\n");
}
finally
{
frame.appendOutputText("Closing sockets...\n");
if (forwardSocket != null)
{
forwardSocket.close();
serverSendPacket = serverReceivePacket = null;
frame.appendOutputText("Forward Socket closed.\n");
}
if (listenSocket != null)
{
listenSocket.close();
frame.appendOutputText("Listen Socket closed.\n");
}
serverSendPacket = serverReceivePacket = null;
clientSendPacket = clientReceivePacket = null;
}
} // End of while loop
}