繁体   English   中英

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

[英]Java socket multiple file transfer over single stream

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


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


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

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

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

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

客户端:复制(fileInputStream,dataOutputStream,长度)

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

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

同样,缓冲区也可以是您喜欢的零以上的任何大小,而缓冲区的大小不会在几个点上蔓延到代码中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM