【发布时间】: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)];
}
}
}
【问题讨论】: