log.info("Request to write file " + wreqPacket.getFilename() + " (" +
file.getAbsolutePath() + ") received from " + packet.getAddress() +
':' + packet.getPort());
fileOut = new FileOutputStream(file);
blockNumber = 0;
bufferedSend(new TFTPAckPacket(packet.getAddress(), packet.getPort(), blockNumber));
clientAddress = packet.getAddress();
clientPort = packet.getPort();
}
break;
case TFTPPacket.DATA:
if (packet.getAddress().equals(clientAddress) && packet.getPort() == clientPort) {
TFTPDataPacket dataPacket = (TFTPDataPacket) packet;
// if client sent next block
if (dataPacket.getBlockNumber() == blockNumber + 1) {
fileOut.write(dataPacket.getData(), dataPacket.getDataOffset(), dataPacket
.getDataLength());
// send acknowledgement
bufferedSend(new TFTPAckPacket(packet.getAddress(), packet.getPort(),
dataPacket.getBlockNumber()));
blockNumber++;
// if last block then end of transfer
if (dataPacket.getDataLength() < TFTPDataPacket.MAX_DATA_LENGTH) {
clientAddress = null;
clientPort = 0;
fileOut.close();
}
}
}
break;
case TFTPPacket.READ_REQUEST:
if (clientAddress == null) {
TFTPReadRequestPacket rreqPacket = (TFTPReadRequestPacket) packet;
try {
File file = new File(".", rreqPacket.getFilename());
log.info("Request to read file " + rreqPacket.getFilename() + " (" +
file.getAbsolutePath() + ") received from " + packet.getAddress() +
':' + packet.getPort());
fileIn = new FileInputStream(file);
blockNumber = 1;
byte[] data = new byte[TFTPDataPacket.MAX_DATA_LENGTH];
final int bytesRead = fileIn.read(data);
bufferedSend(new TFTPDataPacket(packet.getAddress(), packet.getPort(),
blockNumber, data, 0, bytesRead));
// if more blocks to send
if (bytesRead == TFTPDataPacket.MAX_DATA_LENGTH) {
clientAddress = packet.getAddress();
clientPort = packet.getPort();
} else {
fileIn.close();
}
} catch (FileNotFoundException ex) {
bufferedSend(new TFTPErrorPacket(packet.getAddress(), packet.getPort(),
TFTPErrorPacket.FILE_NOT_FOUND, ex.getMessage()));
}
}
break;
case TFTPPacket.ACKNOWLEDGEMENT:
if (packet.getAddress().equals(clientAddress) && packet.getPort() == clientPort) {
TFTPAckPacket ackPacket = (TFTPAckPacket) packet;
// if client acknowledged last block
if (ackPacket.getBlockNumber() == blockNumber) {
// send next block
byte[] data = new byte[TFTPDataPacket.MAX_DATA_LENGTH];
final int bytesRead = fileIn.read(data);
blockNumber++;
bufferedSend(new TFTPDataPacket(packet.getAddress(), packet.getPort(),