-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTFTPClient.java
More file actions
280 lines (236 loc) · 11.6 KB
/
TFTPClient.java
File metadata and controls
280 lines (236 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public class TFTPClient {
private static final int PORT = 1069;
private static final int BLOCK_SIZE = 512;
private static final int TIMEOUT = 5000;
private static final int MAX_RETRIES = 5;
private static final int MAX_THREADS = 4; // Limit number of parallel threads
private static final String CLIENT_FILES_DIR = "clientfiles";
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: java TFTPClient <put|get> <filename> <serverAddress> [username] [password]");
return;
}
String action = args[0];
String filename = args[1];
String serverAddress = args[2];
String username = null;
String password = null;
// Get username and password from command line or prompt
if (args.length >= 5) {
username = args[3];
password = args[4];
} else {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter username: ");
username = scanner.nextLine();
System.out.print("Enter password: ");
password = scanner.nextLine();
}
ExecutorService executor = Executors.newFixedThreadPool(MAX_THREADS);
try (DatagramSocket socket = new DatagramSocket()) {
InetAddress server = InetAddress.getByName(serverAddress);
socket.setSoTimeout(5000);
if (action.equals("get")) {
sendReadRequest(socket, server, filename, username, password);
} else if (action.equals("put")) {
sendWriteRequest(socket, server, filename, username, password, executor);
} else {
System.out.println("Unknown action: " + action);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
executor.shutdown();
}
}
private static void sendReadRequest(DatagramSocket socket, InetAddress server, String filename, String username, String password) throws IOException {
// Create RRQ packet with username and password
ByteBuffer buffer = ByteBuffer.allocate(512);
buffer.putShort((short) 1); // RRQ opcode
// Add username and password
buffer.put(username.getBytes());
buffer.put((byte) 0);
buffer.put(password.getBytes());
buffer.put((byte) 0);
// Add filename and mode
buffer.put(filename.getBytes());
buffer.put((byte) 0);
buffer.put("octet".getBytes());
buffer.put((byte) 0);
DatagramPacket packet = new DatagramPacket(buffer.array(), buffer.position(), server, PORT);
socket.send(packet);
System.out.println("Sent RRQ for file: " + filename + " with username: " + username);
// Start receiving data blocks
receiveFileData(socket, filename);
}
private static void sendWriteRequest(DatagramSocket socket, InetAddress server, String filename,
String username, String password, ExecutorService executor) throws IOException {
// Create WRQ packet with username and password
ByteBuffer buffer = ByteBuffer.allocate(512);
buffer.putShort((short) 2); // WRQ opcode
// Add username and password
buffer.put(username.getBytes());
buffer.put((byte) 0);
buffer.put(password.getBytes());
buffer.put((byte) 0);
// Add filename and mode
buffer.put(filename.getBytes());
buffer.put((byte) 0);
buffer.put("octet".getBytes());
buffer.put((byte) 0);
DatagramPacket packet = new DatagramPacket(buffer.array(), buffer.position(), server, PORT);
socket.send(packet);
System.out.println("Sent WRQ for file: " + filename + " with username: " + username);
// Wait for initial ACK (block 0)
boolean ackReceived = false;
int retries = 0;
while (!ackReceived && retries < MAX_RETRIES) {
try {
DatagramPacket ackPacket = new DatagramPacket(new byte[4], 4);
socket.receive(ackPacket);
ByteBuffer ackBuffer = ByteBuffer.wrap(ackPacket.getData());
short opcode = ackBuffer.getShort();
short blockNum = ackBuffer.getShort();
if (opcode == 4 && blockNum == 0) {
ackReceived = true;
System.out.println("Received initial ACK, starting parallel transmission");
}
} catch (SocketTimeoutException e) {
retries++;
System.out.println("Timeout waiting for initial ACK, retrying...");
socket.send(packet);
}
}
if (!ackReceived) {
System.out.println("Failed to receive initial ACK after " + MAX_RETRIES + " retries");
return;
}
// Start sending data blocks in parallel
sendFileData(socket, server, filename, executor);
}
private static void sendFileData(DatagramSocket socket, InetAddress server, String filename, ExecutorService executor) {
try {
// Read file from clientfiles directory
Path filePath = Paths.get(CLIENT_FILES_DIR, filename);
byte[] fileData = Files.readAllBytes(filePath);
int totalBlocks = (int) Math.ceil((double) fileData.length / BLOCK_SIZE);
AtomicInteger lastBlockSize = new AtomicInteger(fileData.length % BLOCK_SIZE);
if (lastBlockSize.get() == 0) lastBlockSize.set(BLOCK_SIZE);
System.out.println("File size: " + fileData.length + " bytes");
System.out.println("Total blocks: " + totalBlocks);
System.out.println("Last block size: " + lastBlockSize.get() + " bytes");
List<Future<Void>> futures = new ArrayList<>();
CountDownLatch completionLatch = new CountDownLatch(totalBlocks);
AtomicBoolean transferComplete = new AtomicBoolean(false);
// Submit tasks to send each block in parallel
for (int block = 1; block <= totalBlocks; block++) {
final int blockNum = block;
final int start = (block - 1) * BLOCK_SIZE;
final int end = Math.min(start + BLOCK_SIZE, fileData.length);
final byte[] blockData = Arrays.copyOfRange(fileData, start, end);
final boolean isLastBlock = (block == totalBlocks);
System.out.println("Preparing block " + blockNum + ": " + start + " to " + end +
" (size: " + blockData.length + " bytes)");
futures.add(executor.submit(() -> {
String threadName = Thread.currentThread().getName();
try {
sendDataBlock(socket, server, blockNum, blockData, threadName, isLastBlock, lastBlockSize.get());
completionLatch.countDown();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}));
}
// Wait for all blocks to be sent or timeout after 30 seconds
if (!completionLatch.await(30, TimeUnit.SECONDS)) {
System.out.println("Timeout waiting for all blocks to be sent");
} else {
System.out.println("All blocks sent successfully");
}
// Shutdown the executor and wait for all threads to finish
executor.shutdown();
if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
executor.shutdownNow();
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
private static void sendDataBlock(DatagramSocket socket, InetAddress server, int blockNum, byte[] blockData,
String threadName, boolean isLastBlock, int lastBlockSize) throws IOException {
ByteBuffer dataBuffer = ByteBuffer.allocate(4 + blockData.length);
dataBuffer.putShort((short) 3); // DATA opcode
dataBuffer.putShort((short) blockNum);
dataBuffer.put(blockData);
DatagramPacket dataPacket = new DatagramPacket(dataBuffer.array(), dataBuffer.array().length, server, PORT);
boolean ackReceived = false;
int retries = 0;
while (!ackReceived && retries < MAX_RETRIES) {
try {
socket.send(dataPacket);
System.out.println("Thread " + threadName + " sent block " + blockNum +
(isLastBlock ? " (last block)" : "") + " (size: " + blockData.length + " bytes)");
DatagramPacket ackPacket = new DatagramPacket(new byte[4], 4);
socket.receive(ackPacket);
ByteBuffer ackBuffer = ByteBuffer.wrap(ackPacket.getData());
short opcode = ackBuffer.getShort();
short receivedBlockNum = ackBuffer.getShort();
if (opcode == 4 && receivedBlockNum == blockNum) {
System.out.println("Thread " + threadName + " received ACK for block " + blockNum);
ackReceived = true;
}
} catch (SocketTimeoutException e) {
retries++;
System.out.println("Thread " + threadName + " timeout for block " + blockNum + ", retry " + retries);
}
}
if (!ackReceived) {
System.out.println("Thread " + threadName + " failed to receive ACK for block " + blockNum +
" after " + MAX_RETRIES + " retries");
}
}
private static void receiveFileData(DatagramSocket socket, String filename) throws IOException {
FileOutputStream fileOutputStream = new FileOutputStream(new File(CLIENT_FILES_DIR, filename));
int blockNum = 1;
boolean lastBlock = false;
while (!lastBlock) {
DatagramPacket dataPacket = new DatagramPacket(new byte[516], 516);
socket.receive(dataPacket);
ByteBuffer buffer = ByteBuffer.wrap(dataPacket.getData(), 0, dataPacket.getLength());
short opcode = buffer.getShort();
short receivedBlockNum = buffer.getShort();
byte[] data = new byte[dataPacket.getLength() - 4];
buffer.get(data);
if (opcode == 3 && receivedBlockNum == blockNum) {
// Write received data to the file
fileOutputStream.write(data);
System.out.println("Received block " + blockNum + " (size: " + data.length + " bytes)");
// Send ACK
ByteBuffer ackBuffer = ByteBuffer.allocate(4);
ackBuffer.putShort((short) 4); // ACK opcode
ackBuffer.putShort(receivedBlockNum);
DatagramPacket ackPacket = new DatagramPacket(ackBuffer.array(), ackBuffer.array().length,
dataPacket.getAddress(), dataPacket.getPort());
socket.send(ackPacket);
System.out.println("Sent ACK for block " + blockNum);
// If the received block is less than BLOCK_SIZE, it's the last block
if (data.length < BLOCK_SIZE) {
lastBlock = true;
System.out.println("Received last block");
}
blockNum++;
}
}
fileOutputStream.close();
System.out.println("File transfer complete");
}
}