【问题标题】:Transferring file from client to server将文件从客户端传输到服务器
【发布时间】:2014-05-24 02:19:52
【问题描述】:

我正在尝试将文本 .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 对象)并返回。
任何帮助将不胜感激。

【问题讨论】:

    标签: java file client-server


    【解决方案1】:

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

    解决方案...

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

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

    【讨论】:

    • 向服务器发送字节数是个好主意。谢谢。
    【解决方案2】:

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

    【讨论】:

    • 我无法关闭流 - 我需要它来进行客户端和服务器之间的进一步通信和数据传输。而且我无法删除 while 循环 - 服务器不知道从客户端接受多少字节,它无法预测文件大小......
    • 流上有available()函数
    • 或者什么要发送第一个字节的大小?
    • 是的,我想我会同意的。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2019-07-12
    • 2016-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-16
    相关资源
    最近更新 更多