这对于这个问题来说为时已晚,但可能对像我这样的人有用。
private int bufferSize = 1024;
/**
* Sending the reply.
*/
public void sendReply() {
DatagramPacket qPacket = null;
DatagramPacket reply = null;
int port = 8002;
try {
// Send reply.
if (qPacket != null) {
byte[] tmpBuffer = new byte[bufferSize];
System.arraycopy(buffer, 0, tmpBuffer, 0, bufferSize);
reply = new DatagramPacket(tmpBuffer, tmpBuffer.length,
qPacket.getAddress(), port);
socket.send(reply);
}
} catch (Exception e) {
logger.error(" Could not able to recieve packet."
+ e.fillInStackTrace());
}
}
/**
* Receives the UDP ping request.
*/
public void recievePacket() {
DatagramPacket dPacket = null;
byte[] buf = new byte[bufferSize];
try {
while (true) {
dPacket = new DatagramPacket(buf, buf.length);
socket.receive(dPacket);
// This is a global variable.
bufferSize = dPacket.getLength();
sendReply();
}
} catch (Exception e) {
logger.error(" Could not able to recieve packet." + e.fillInStackTrace());
} finally {
if (socket != null)
socket.close();
}
}