0

我已经制作了服务器客户端应用程序,服务器将向客户端发送文件,客户端将接收它并将其保存在 C:/ 中的任何位置。我首先发送一个字符串“文件”以告诉客户端接收文件,然后服务器将文件名和大小发送给客户端,然后开始发送它。问题是客户端没有接收文件,尽管它在循环中读取并获取所有字节但没有写入所需的文件对象。请查看我显示的客户代码

以下是服务器代码:

public void run(){
    try{
        System.out.println("Starting writing file");
        objOut.writeObject("File");
        objOut.flush();

        File f= new File(filePath);
        String name= f.getName();
        int length =(int) f.length();
        objOut.writeObject(name);
        objOut.flush();

        objOut.writeObject(length);
        objOut.flush();

        byte[] filebytes = new byte[(int)f.length()];
        FileInputStream fin= new FileInputStream(f);
        BufferedInputStream bin = new BufferedInputStream(fin);

        bin.read(filebytes, 0, filebytes.length);
        BufferedOutputStream bout = new BufferedOutputStream(objOut);
        bout = new BufferedOutputStream(objOut);
        bout.write(filebytes, 0, filebytes.length);
        bout.flush();      
        System.out.println("File completelty sent");

    }
    catch(Exception ex)
    {
        System.out.println("error on writing file : "+ex.getMessage());
    }

}

以下是客户端代码:

 while(true){
            fobjIn = new ObjectInputStream(fileSock.getInputStream());
            String str = (String) fobjIn.readObject();
            if(str.equals("File"))
            {
                System.out.println("Starting receiving file");
                ReceiveFile();
            }
            System.out.println(str);
        }

 public void ReceiveFile() throws Exception{

     String name =(String)fobjIn.readObject();
   File f = new File("C:/Temp/" +name);
   f.createNewFile();
   int length = (int) fobjIn.readObject();
   FileOutputStream fout = new FileOutputStream(f);
   BufferedOutputStream buffout = new BufferedOutputStream(fout);
   byte[] filebyte = new byte[length];
   int bytesRead=0,current=0;
   bytesRead = fobjIn.read(filebyte, 0, filebyte.length);
    do {
        bytesRead = fobjIn.read(filebyte, current, (filebyte.length-current));
        if(bytesRead > 0) {
            current += bytesRead;
            System.out.println("writting" + bytesRead);
        }
        else break;
     } while(bytesRead > -1);

^^^^^^^ 乞求时它不会从循环中出来^^^^^^^^

    buffout.write(filebyte, 0 , current);
    buffout.flush();
    System.out.println("written");

}
4

1 回答 1

2

完成发送后,您可能应该在服务器端关闭您的流,以便可以通知客户端服务器已完成发送。否则它只会坐在那里等待更多数据。

于 2013-01-28T14:10:41.417 回答