我正在编写一个简单的FTP客户端/服务器设置。客户端应该能够从服务器检索文件并将结果作为字节流放入/ retr_files / filex。从服务器发送适当的响应,并确实在文件夹中创建了file1。但是,发送(或接收)的字节太多。我在一个9.6kB文件上测试了它,它在客户端的文件是16.6kB。奇。我觉得我在这里遗漏了一些明显的东西,有人可以帮帮我吗? 谢谢!
相关代码:
客户端:
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();
服务器:
//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();
}
答案 0 :(得分:2)
不要使用Readers and Writers和readLine()。所有文件都不是文本文件,并非所有文本文件都有换行符。使用流。
答案 1 :(得分:0)
我想在您的客户端,新创建的文件必须在每个打印行之间有额外的新行。这可能会导致文件大小增加。 在客户端替换这一行:
bufferedWriter.write(length + "\n");
要
bufferedWriter.write(length);