Java套接字通过单个流传输多个文件

时间:2014-05-06 10:13:29

标签: java sockets stream

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


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


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

我修改了一个流复制方法,以确保复制不会从传入和传出流中复制太多数据。此复制方法在服务器和客户端上用于发送和接收。

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

服务器: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)];
        }
    }
}

1 个答案:

答案 0 :(得分:-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);
        }
    }

E&安培; OE

这样,缓冲区可以是你喜欢的任何大小都是零,而不是它的大小在几个点上蔓延到代码中。

相关问题