Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 通过套接字发送文件(服务器端线程)-不工作_Java - Fatal编程技术网

Java 通过套接字发送文件(服务器端线程)-不工作

Java 通过套接字发送文件(服务器端线程)-不工作,java,Java,我有一个客户机-服务器程序。客户端程序向服务器发送一个文件,服务器接收该文件。我的问题是,该文件没有在服务器上真正接收…我没有在服务器目录中创建file.txt,但它是空的…(是的,我确定客户端目录中的ne file.txt不是空的;) 我认为问题在于Client.java中的while循环,因为它从来不会让人尴尬 对于未来,我现在在服务器端实现每个接收文件一个线程 客户端程序: package controller; public class Main { pub

我有一个客户机-服务器程序。客户端程序向服务器发送一个文件,服务器接收该文件。我的问题是,该文件没有在服务器上真正接收…我没有在服务器目录中创建file.txt,但它是空的…(是的,我确定客户端目录中的ne file.txt不是空的;) 我认为问题在于Client.java中的while循环,因为它从来不会让人尴尬

对于未来,我现在在服务器端实现每个接收文件一个线程

客户端程序:

   package controller;

   public class Main {

       public static void main(String[] args) {
           new Controller();
    }

}
    import java.io.IOException;


    public class Main {

        public static void main(String[] args) throws IOException {
            new Server();
        }

    }
-

-

服务器程序:

   package controller;

   public class Main {

       public static void main(String[] args) {
           new Controller();
    }

}
    import java.io.IOException;


    public class Main {

        public static void main(String[] args) throws IOException {
            new Server();
        }

    }
-

-


在执行此类传输时,您必须记住套接字的关闭关闭之间存在差异,在代码中,您关闭客户端中的套接字

让我们看看会发生什么:填充缓冲区,然后告诉套接字关闭,这将放弃您刚才请求的操作。 关闭时,您会告诉套接字“我不会发送更多数据,但会发送剩下的数据并关闭”,因此您需要做的是在关闭套接字之前关闭它,以便数据能够到达

所以不是这个

out.flush();

out.close();
fis.close();
bis.close();
socket.close();
试试这个

out.flush();

socket.shutdownInput();    // since you only send you may not need to call this
socket.shutdownOutput();   // with this you ensure that the data you "buffered" is sent
socket.close();

一般来说,如果您想要一个优雅的关闭,您应该在所有情况下都这样做,即使对于服务器也是如此,因此如果出现错误,您所做的通常是可以的,因为您无法从错误中恢复,所以您只需关闭连接。

我尝试过,但它仍然不起作用。。。。。但是在尝试了您的代码示例之后,我尝试删除版本“socket.close();”中的最后一行。如果我这样做了,那么它就成功了!但它必须关闭这个套接字,或者?就像我说的,它对我来说是这样工作的,这里的问题是,在发送所有数据之前关闭,所以如果不关闭,这是一种使它工作的方法,但仍然不是你想要做的。那么flush()没有阻塞吗?如果没有,为什么我使用Thread.sleep(5000)时它不起作用;在out.flush()之后?我在这里发送了一个5KB的文件,所以5秒钟就足够了。
out.flush();

socket.shutdownInput();    // since you only send you may not need to call this
socket.shutdownOutput();   // with this you ensure that the data you "buffered" is sent
socket.close();