简体   繁体   English

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

[英]Java socket multiple file transfer over single stream

I have written a client-server file transfer program. 我已经编写了一个客户端-服务器文件传输程序。 I am trying to achieve the following workflow: 我正在尝试实现以下工作流程:


connect to server -> open stream -> authenticate -> mesage('Send File') -> message([file name]) -> message([file size]) -> send the file -> message('Send File') ... message('Disconnect') 连接到服务器->打开流->身份验证->消息(“发送文件”)->消息([文件名])->消息([文件大小])->发送文件->消息(“发送文件” )...消息(``断开连接'')


The goal is to only connect and authenticate once and send multiple files over a single dataStream. 目标是仅连接和验证一次,并通过单个dataStream发送多个文件。

I have modified a stream copying method to make sure the copying does not copy too much data from the incoming and outgoing stream. 我修改了流复制方法,以确保复制不会从传入和传出流中复制太多数据。 This copy method is used on both the server and client for sending and receiving. 在服务器和客户端上都使用此复制方法进行发送和接收。

example sending a file from client to server: 从客户端向服务器发送文件的示例:

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

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

My question is do you see any potential problems with this approach? 我的问题是,您认为这种方法有潜在的问题吗?

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

The easy way to do that is as follows: 这样做的简单方法如下:

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

E&OE E&OE

This way too, the buffer can be any size you like above zero without its size creeping into the code at several points. 同样,缓冲区也可以是您喜欢的零以上的任何大小,而缓冲区的大小不会在几个点上蔓延到代码中。

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

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