1

我已经编写了通过套接字传输文件的代码,文件传输正确,但即使在调用.close()方法后也没有关闭。

但是文件在关闭“套接字”后关闭,但我想保持连接打开。

这里服务器将文件发送给客户端

服务器代码

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();
}

客户代码:

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();
}

代码有什么问题?

4

1 回答 1

0

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

于 2013-03-13T10:09:40.887 回答