我正在编写一个简单的 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();
}