I'm writing a simple FTP client/server setup. The client is supposed to be able to retrieve a file from the server and place the result as a stream of bytes into /retr_files/filex. The appropriate responses are sent from the server, and file1 is indeed created in the folder. However, too many bytes were sent (or received). I tested this on a 9.6kB file and the file it made client-side was 16.6kB. Odd. I feel like I'm missing something obvious here, can someone help me out? Thanks!
Relevant code:
Client:
BufferedReader inFromServer_d = null;
if(welcomeSocket!=null){
if(!welcomeSocket.isClosed()){
welcomeSocket.close();
}
}
try {
welcomeSocket = new ServerSocket(port);
System.out.print("PORT " + myIP + "," + num1 + "," + num2 + "\r\n");
out.writeBytes("PORT " + myIP + "," + num1 + "," + num2 + "\r\n");
System.out.print(parseReply(getResponse()));
System.out.print("RETR " + pathname + "\r\n");
out.writeBytes("RETR " + pathname + "\r\n");
String reply = parseReply(getResponse());
if (reply.charAt(10)=='1') {
System.out.print(reply);
System.out.print(parseReply(getResponse()));
try{
clientSocket_d = welcomeSocket.accept();
} catch (IOException e) {
System.out.print("GET failed, FTP-data port not allocated.\r\n");
System.exit(-1);
}
inFromServer_d = new BufferedReader(new InputStreamReader(
clientSocket_d.getInputStream()));
// READ
BufferedReader bufferedReader = inFromServer_d;
FileWriter output = new FileWriter("retr_files/file" + retrCnt);
BufferedWriter bufferedWriter = new BufferedWriter(output);
String length;
while ((length = bufferedReader.readLine()) != null) {
bufferedWriter.write(length + "\n");
}
bufferedReader.close();
bufferedWriter.close();
clientSocket_d.close();
Server:
//TCP CONNECT
DataOutputStream outToClient_d = null;
Socket clientSocket1 = null;
try {
ipAddress = ipAddress.substring(0, ipAddress.length()-1);
clientSocket1 = new Socket(ipAddress, portNumber);
outToClient_d = new DataOutputStream(clientSocket1.getOutputStream());
}
catch(UnknownHostException e){
out.writeBytes("425 Can not open data connection.\r\n");
}
BufferedReader bufferedReader = new BufferedReader(input);
String length;
while((length = bufferedReader.readLine())!=null){
outToClient_d.writeBytes(length+"\n");
}
out.writeBytes("250 Requested file action completed.\r\n");
bufferedReader.close();
clientSocket1.close();
outToClient_d.close();
}
Don't use Readers and Writers and readLine(). All files are not text files, and not all text files have line breaks. Use streams.
I guess at your client side , the newly created file must have extra new line between each printed lines. That might lead to increase in size of file. AT client side replace this line :
bufferedWriter.write(length + "\n");
To
bufferedWriter.write(length);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.