【发布时间】:2014-09-30 23:28:55
【问题描述】:
我有一对使用 TCP 协议的简单客户端/服务器 FTP 类。我可以传输小文本文件,但是当我尝试使用像 this 这样的更大文件时,文件似乎已损坏(编辑器在试图打开它时被锁定,更少被卡住跳到最后。)我有一种感觉'没有正确关闭它,或者从套接字正确读取和保存它。这是来自客户端和服务器的 get() 函数。希望有人能发现我做错了什么。
服务器:
public void get(){
// get file path from client
try {
this.filePath = controlIn.readLine();
} catch (IOException e) {
controlOut.println(ERROR);
dataOut.println("Server Error: Unable to read file path");
System.out.println("error reading filepath");
return;
}
// if client sends 0, abort GET (file exists in client directory)
if(filePath == "-1"){
return;
}
// check if file exists
File f = new File(filePath);
if(!f.exists()){
controlOut.println(ERROR);
dataOut.println("Server Error: File does not exist: " + filePath);
return;
}
// send file size as success msg
int fileSize = (int)f.length();
controlOut.println(fileSize);
//read file to buffer, write buffer to socket
byte [] buf = new byte [fileSize];
try {
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(buf,0,buf.length);
OutputStream os = dataSocket.getOutputStream();
os.write(buf,0,fileSize);
fis.close();
bis.close();
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
客户:
public void get(String filePath){
// check if file exists. If not, send ERROR to server
File f = new File(filePath);
if(f.exists()){
controlOut.println(ERROR);
System.out.println("Client Error: File: " + filePath + " already exists");
return;
}
// send file path to server
controlOut.println(filePath);
// read status from server. Status > 0 = file size
int status = readStatus();
if(status == ERROR){
System.out.println(readError());
return;
}
int fileSize = status;
int bytesRead;
int totalBytesRead = 0;
byte [] buf = new byte [fileSize*2];
try {
InputStream is = dataSocket.getInputStream();
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(fos);
do{
bytesRead = is.read(buf,0,fileSize);
} while(bytesRead != -1);
bos.write(buf, 0 , fileSize);
is.close();
bos.close();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
还有一件事。 get方法返回后,服务器端关闭数据套接字,客户端的fileSize似乎是正确的。
【问题讨论】:
-
你能用 ls 来获取文件大小吗?
-
如果您的意思是让我现在查看这两个文件,它们是相同的。都是 3206080 字节。
-
您的 while 循环是错误的(您在循环中读取,但不是在循环内写入),并且您不需要巨大的缓冲区。 8192 字节就足够了。
-
哦,是的,我明白了。谢谢。