【问题标题】:Socket file transfer: Receiver stuck in reading from buffer/writing to storage套接字文件传输:接收器卡在从缓冲区读取/写入存储中
【发布时间】:2012-07-14 15:18:31
【问题描述】:
static void sendFile(Socket socket, File file) throws IOException {

    File testFile = new File( Environment.getExternalStorageDirectory().toString()+"/DCIM/Camera/Test.jpg");
    byte [] buffer = new byte[(int)testFile.length()];
    FileInputStream fis = new FileInputStream(testFile);
    BufferedInputStream bis = new BufferedInputStream(fis);
    Log.d(DebugTag, "Trying to read testFile from storage into buffer");
    bis.read(buffer,0,buffer.length); 
    Log.d(DebugTag, "Read testFile into buffer");
    OutputStream os = socket.getOutputStream();
    Log.d(DebugTag, "Trying to write testFile from buffer into output stream");
    os.write(buffer, 0, buffer.length);
    Log.d(DebugTag, "Wrote testFile from buffer into output stream");
    os.flush();
    Log.d(DebugTag, "Outputstream flushed");
}

static void receiveFile(Socket socket) throws IOException {

    InputStream is = socket.getInputStream();
    String receivedFileDirectory = Environment.getExternalStorageDirectory().toString()+"/Pictures/receivedFile.jpg";
    File receivedFile = new File(receivedFileDirectory);
    //check if directory exists, otherwise create it
    if (receivedFile.exists()) {
        Log.d(DebugTag, "Filename at destination already exists");
    } else if (!receivedFile.exists()) {
        Log.d(DebugTag, "Filename at destination does not exist, trying to create it!");
        receivedFile.createNewFile();
        Log.d(DebugTag, "Created file!");
    }

    Log.d(DebugTag, "Preparing file reception. Destination:"+receivedFileDirectory);
    OutputStream os = new FileOutputStream(receivedFileDirectory);
    Log.d(DebugTag, "established outputstream to file directory");
    byte[] buffer = new byte[2048];
    int length;
    Log.d(DebugTag, "Trying to read inputstream into buffer and write file to destination");
    while ((length = is.read(buffer)) >0 ) {
        os.write(buffer,0,length);
    }
    Log.d(DebugTag, "File received.");
    os.flush();
    os.close();
    is.close();
    Log.d(DebugTag, "Closed in and out streams");

}

发件人文件似乎工作正常,我收到每条日志消息,直到“输出流被刷新”。 在接收方,一切似乎都很顺利,直到代码到达 while 循环:我得到的最后一个日志消息总是“尝试将输入流读入缓冲区并将文件写入目标”,而不是“收到文件”和以下消息.奇怪的是:我收到了测试文件并可以打开它(尽管需要几秒钟 - 不知道这是否适用于 android)。 代码卡在 while 循环中的任何线索?

第二个问题:这是我的第一个 Android/Java 应用程序。这段代码可以通过套接字发送和接收文件吗?即使文件变大(高达 >100MB)?

提前致谢!

【问题讨论】:

    标签: java android sockets inputstream file-transfer


    【解决方案1】:

    is.read(buffer) 只会在连接的另一端正常关闭(或在错误时抛出异常)时返回零,所以您缺少的是发送端的 socket.close()

    os.flush() 在这里还不够,因为 TCP 不知道您何时完成发送数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-15
      • 1970-01-01
      • 2012-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多