简体   繁体   中英

java socket fileoutputstream can't close file

i've write a code for transferring file over sockets, the file is transfers properly but it isn't closed even after calling .close() method.

however the file closes after closing the "sockets", but i want to keep the connection open.

here the server sends the file to client

SERVER CODE

public  void sendFile(String sfileName) throws IOException{
    try{
        in = new FileInputStream(sfileName);
        out = socket.getOutputStream();
        transferData(in,out);
    }
    finally {
        in.close();
        in = null;
        System.gc();
    }
}
private void transferData(InputStream in, OutputStream out) throws IOException  {
    byte[] buf = new byte[8192];
    int len = 0;
    while(in.available()==0);
    while ((len = in.read(buf)) != -1) {
    out.write(buf, 0, len);
    }
    out.flush();
}

CLIENT CODE :

public  void recieveFile(String rfileName) throws IOException{
    try{
        in = socket.getInputStream();
        System.out.println("Reciever file : " + rfileName);
        out = new FileOutputStream(rfileName);
        transferData(in,out);
    }
    finally{
        out.flush();
        out.close();
        out = null;
        System.gc();
    }
}
private void transferData(InputStream in, OutputStream out) throws IOException  {
    byte[] buf = new byte[8192];
    int len = 0;
    while(in.available()==0);
    while ((len = in.read(buf)) != -1) {
    out.write(buf, 0, len);
    }
    out.flush();
}

what is wrong with the code ?

我认为您应该使用Socket.shutdownOutput()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM