[英]How do I make a loop to read/download file from server (in client-server application)?
In my client-server application, the client sends GET filename
command to the server in order to download the file. 在我的客户端服务器应用程序中,客户端将
GET filename
命令发送到服务器以下载文件。 Now the client must be able to read the buffer size (of file residing in server) and download it into the client. 现在,客户端必须能够读取(在服务器中的文件的)缓冲区大小并将其下载到客户端中。 That's I have done inside a while loop.
那是我在while循环内完成的。 My concern is about that loop in client class: Is the looping correct?
我担心的是客户端类中的循环:循环正确吗? The way I am reading the file ...?
我正在读取文件的方式...?
I think I should specify the filesize inside the loop. 我想我应该在循环内指定文件大小。 Then how it could be done or improved?
那么如何做到或改进呢?
This is the portion of code I am working on. 这是我正在处理的代码部分。
ClientSide: 客户端:
if (request.startsWith("GET")) {
File file = new File(request.substring(4));
is = socket.getInputStream();
fos = new FileOutputStream(file);
byte[] buffer = new byte[socket.getReceiveBufferSize()];
int bytesReceived = 0;
while ((bytesReceived = is.read(buffer)) >=0) {
//while ((bytesReceived = is.read(buffer))>=buffer) {
fos.write(buffer, 0, bytesReceived);
}
request = "";
fos.close();
is.close();
}
ServerSide: 服务器端:
try (FileInputStream fis = new FileInputStream(file)) {
os = socket.getOutputStream();
byte[] buffer = new byte[(1 << 7) - 1];
int bytesRead = 0;
while ((bytesRead = fis.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
}
If this is an implementation of HTTP protocol, the client might not not the size of the file, which is being send by the server. 如果这是HTTP协议的实现,则客户端可能不是服务器正在发送的文件大小。 One approach is the server always sends "Content-Length" header and client reads up to this length.More info HTTP specification: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html The other approach is client reads until the connection is closed by the server.
一种方法是服务器始终发送“ Content-Length”标头,客户端读取此长度。更多信息HTTP规范: http : //www.w3.org/Protocols/rfc2616/rfc2616-sec14.html另一种方法是客户端读取直到服务器关闭连接。 When server sends the whole file, it closes the connection.
服务器发送整个文件时,它将关闭连接。 This is not very reliable, as connection might be dropped due to network problem.
这不是很可靠,因为由于网络问题,连接可能会断开。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.