Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/380.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java socket单流多文件传输_Java_Sockets_Stream - Fatal编程技术网

Java socket单流多文件传输

Java socket单流多文件传输,java,sockets,stream,Java,Sockets,Stream,我已经编写了一个客户机-服务器文件传输程序。我正在尝试实现以下工作流: 连接到服务器->开放流->身份验证->mesage('发送文件')->消息([文件名])->消息([文件大小])->发送文件->消息('发送文件')。。。消息('断开连接') 目标是只进行一次连接和身份验证,并通过单个数据流发送多个文件 我修改了流复制方法,以确保复制不会从传入和传出流复制太多数据。此复制方法在服务器和客户端上都用于发送和接收 将文件从客户端发送到服务器的示例: 服务器:复制(dataInputStrea

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


连接到服务器->开放流->身份验证->mesage('发送文件')->消息([文件名])->消息([文件大小])->发送文件->消息('发送文件')。。。消息('断开连接')


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

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

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

服务器:复制(dataInputStream、fileOutPutStream、长度)

客户端:复制(文件输入流、数据输出流、长度)

我的问题是,你认为这种方法有任何潜在的问题吗

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)];
        }
    }
}
static void copy(InputStream-in、OutputStream-out、long-length)抛出IOException{
字节[]buf;
如果(长度<8192){
buf=新字节[(int)长度];
}
buf=新字节[8192];
int len=0;
长读=0;
而(长度>读取&(len=in.read(buf))>-1){
read+=len;
out.write(buf,0,len);
如果(长度-读数<8192){
buf=新字节[(int)(长度-读取)];
}
}
}
E&OE

通过这种方式,缓冲区可以是大于零的任意大小,而不会在代码中的多个点上爬行

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);
        }
    }