【问题标题】:Java socket multiple file transfer over single streamJava套接字通过单个流传输多个文件
【发布时间】:2014-05-06 10:13:29
【问题描述】:

我写了一个客户端-服务器文件传输程序。我正在尝试实现以下工作流程:


连接到服务器->打开流->验证->消息('发送文件')->消息([文件名])->消息([文件大小])->发送文件->消息('发送文件') ... message('断开连接')


目标是只连接和验证一次,并通过单个数据流发送多个文件。

我已经修改了流复制方法,以确保复制不会从传入和传出流中复制太多数据。服务端和客户端都使用这种复制方式进行发送和接收。

从客户端向服务器发送文件的示例:

服务器: copy(dataInputStream, fileOutPutStream, length)

客户端: copy(fileInputStream, dataOutputStream, length)

我的问题是,您认为这种方法有什么潜在的问题吗?

static void copy(InputStream in, OutputStream out, long length) throws IOException {
    byte[] buf;
    if (length < 8192) {
        buf = new byte[(int) length];
    }
    buf = new byte[8192];
    int len = 0;
    long read = 0;
    while (length > read && (len = in.read(buf)) > -1) {
        read += len;
        out.write(buf, 0, len);
        if (length - read < 8192) {
            buf = new byte[(int) (length - read)];
        }
    }
}

【问题讨论】:

    标签: java sockets stream


    【解决方案1】:
    while (length > read && (len = in.read(buf)) > -1) {
            read += len;
            out.write(buf, 0, len);
            if (length-read < 8192){
                buf = new byte[(int) (length-read)];
            }
        }
    

    简单的方法如下:

    while (length > read && (len = in.read(buf, 0, Math.min(buf.length, length-read))) > 0) {
            read += len;
            out.write(buf, 0, len);
            }
        }
    

    电子与工程

    通过这种方式,缓冲区也可以是您喜欢的大于零的任何大小,而不会在多个点处蔓延到代码中。

    【讨论】:

      猜你喜欢
      • 2020-12-02
      • 1970-01-01
      • 2018-08-19
      相关资源
      最近更新 更多