我正在用java制作一个简单的FTP服务器。当我在本地测试它(在我自己的机器上运行服务器和客户端)时,我一切正常。但是,当我在两台不同的远程计算机上运行服务器和客户端时,客户端在收到来自服务器的“150 文件状态正常”消息后不久就会挂起。我不明白为什么它在一个地方工作得很好,而在另一个地方却不行。以下是相关代码:
服务器(发送文件):
FileInputStream input = null;
try {
input = new FileInputStream(filePath);
} catch (FileNotFoundException e) {
out.writeBytes("550 File not found or access denied.\r\n");
}
out.writeBytes("150 File status okay.\r\n");
// 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");
}
byte[] buf = new byte[2048];
int len;
while ((len = input.read(buf)) > 0) {
outToClient_d.write(buf, 0, len);
}
input.close();
out.writeBytes("250 Requested file action completed.\r\n");
clientSocket1.close();
outToClient_d.close();
客户端(将文件保存到 /retr_files):
InputStream 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 = clientSocket_d.getInputStream();
// READ
InputStream input = inFromServer_d;
OutputStream output = new FileOutputStream("retr_files/file"
+ retrCnt);
byte[] buf = new byte[2048];
int len;
while ((len = input.read(buf)) > 0) {
output.write(buf, 0, len);
}
input.close();
output.close();
clientSocket_d.close();
} else {
System.out.print(reply);
}
} catch (IOException e) {
System.out.print("GET failed, FTP-data port not allocated.\r\n");
System.exit(-1);
}
任何帮助表示赞赏!