我用Java编写了一个Server-Client应用程序。客户端应该发送目录的内容,而Server必须保存它。不幸的是,它不适用于大于~8 kb的文件。在尝试发送20kb文件后,客户端表示它已成功发送文件,但看起来Server仍在等待数据接收。为什么不起作用?客户端是否可能在服务器从中读取所有内容之前关闭流?如果是,我该如何解决?
客户端:
@Override
public void run() {
try {
Socket s = new Socket(ip, port);
BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
DataOutputStream dos = new DataOutputStream(bos);
DataInputStream dis = new DataInputStream(s.getInputStream());
dos.writeInt(fileNames.size());
int k = 0;
for(File f : filesToSend) {
dos.writeLong(f.length());
System.out.println(f.length());
dos.writeUTF(fileNames.get(k));
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
int oneByte;
long bytesSend = 0;
long startTime = System.currentTimeMillis();
long timeElapsed;
for(int i = 0 ; i < f.length() ; i++) {
bytesSend++;
bos.write(bis.read());
timeElapsed = System.currentTimeMillis();
speed = ((startTime - timeElapsed) / 60) / bytesSend;
refresh.refreshLabels(speed, fileNames.get(k));
}
System.out.println("File "+fileNames.get(k)+" successfully sent");
k++;
fis.close();
bis.close();
}
} catch (IOException ex) {
Logger.getLogger(FileSenderSocket.class.getName()).log(Level.SEVERE, null, ex);
}
服务器:
public void downloadFiles() throws IOException {
BufferedInputStream bis = new BufferedInputStream(activeSocket.getInputStream());
DataInputStream dis = new DataInputStream(bis);
DataOutputStream dos = new DataOutputStream(activeSocket.getOutputStream());
int filesCount = dis.readInt();
System.out.println("Number of files: "+filesCount);
File[] files = new File[filesCount];
for(int j = 0 ; j < filesCount ; j++) {
long fileLength = dis.readLong();
String fileName = dis.readUTF();
System.out.println("Recieving file \""+fileName+"\"");
String[] temp = (fileName).split("/");
if(temp.length > 1) {
String dir = "";
for(int k = 0 ; k < temp.length-1 ; k++) dir+=temp[k];
File dirF = new File(path.getText()+dir);
dirF.mkdirs();
}
files[j] = new File(path.getText()+fileName);
System.out.println("File Created");
FileOutputStream fos = new FileOutputStream(files[j]);
BufferedOutputStream bos = new BufferedOutputStream(fos);
System.out.println("File length: "+fileLength);
for(int i=0 ; i < fileLength ; i++) bos.write(bis.read());
bos.close();
System.out.println("File \""+fileName+"\" recieved and saved");
}
dis.close();
}
提前致谢
编辑:事实证明,Server只能接收24469个字节。当它达到24470字节时,它只是暂停。