如何停止socket继续在循环java中写入数据

时间:2013-01-28 14:06:08

标签: java file sockets

我已经建立了服务器客户端应用程序,其中服务器将文件发送到客户端,客户端将接收它并将其保存在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");

}

1 个答案:

答案 0 :(得分:2)

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