将文件从客户端传输到服务器

时间:2014-05-23 17:41:23

标签: java file client-server

我正在尝试将文本.txt文件从客户端简单地传输到服务器,无论我认为我知道多少,并了解我在做什么,以及究竟发生了什么,我总是弄错。我真的可以在这里使用一些帮助。

所以,这是代码,两个将.txt文件从一个文件转移到另一个文件的函数:
客户方:

private void sendFileToServer(String file_name) throws IOException {

    File file=new File(file_name);
    int file_size=(int)file.length();
    byte[] bytes=new byte[file_size];
    FileInputStream os=null;
    try {
        os = new FileInputStream(file);
    } catch (FileNotFoundException e) {
        System.out.println("The file "+file+" wasn't found");
        return;
    }
    BufferedInputStream bos=new BufferedInputStream(os);

    bos.read(bytes);
    output.write(bytes,0,bytes.length);
    /* 'output' is a PrintStream object, that holds the output stream
     * for the client's socket, meaning:
     * output=new PrintStream(client_socket.getOutputStream()); */
    output.flush();
    bos.close();
}

这会将所有内容缓冲到BufferedInputStream,将其复制到bytes,然后将其发送到另一方 - 服务器。
服务器端:

public static String receiveFileFromClient(Client client) throws IOException {

    int buffer_size=client.getSocket().getReceiveBufferSize();
    byte[] bytes=new byte[buffer_size];
    FileOutputStream fos=new FileOutputStream("transfered_file.txt");
    BufferedOutputStream bos=new BufferedOutputStream(fos);

    DataInputStream in=client.getInputStream();

    int count;
    System.out.println("this will be printed out");
    while ((count=in.read(bytes))>0) { // execution is blocked here!
        bos.write(bytes, 0, count);
    }
    System.out.println("this will not be printed");
    bos.flush();
    bos.close();

    return "transfered_file.txt";

}

我的目的是继续从客户端(while循环)读取字节,直到另一方(客户端)没有更多的字节要发送,这就是in.read(bytes)应该在哪里返回0并且循环应该中断,但是这种情况永远不会发生,它会被阻止,即使客户端输入流中的所有字节都已成功传输!
为什么循环没有中断?
来自Javadoc:

  

如果没有字节可用,因为流位于文件末尾,则   值-1返回

最后一个字节是不是被认为是“文件结束”?我确保函数sendFileToServer正确地将整个文件写入output实例(PrintStream对象)并返回。
任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

如果你不关闭流,

read()方法将阻止进一步输入。因此,关闭流,或删除循环,只读取您从客户端收到的字节数

答案 1 :(得分:1)

据我了解,read()方法将阻塞,直到它读取[bytes]或者套接字关闭。所以read()什么都没有表明它应该停止阅读,因为它不“理解”文件,只是一些数据。

解决方案......

您可以确定客户端将发送的字节数(在客户端),然后将NUMBER发送到服务器。现在,服务器可以处理此数字,并知道在文件完成之前要读取的字节数。因此,您可以在传输完成时中断循环(甚至不使用循环)。

您还可以处理服务器接收的数据,并在文件完成后让客户端发送一些“标志”,以便服务器知道何时完成。但这更难,因为你必须找到一些不包含在文件字节数据中的东西