1
如何使用套接字計算下載的數據量和要下載的總數據。如何計算下載的文件大小和要下載的總數據
E.G. 500kb/95000kb ... 95000kb/95000kb
這裏我包含了我的代碼供您參考。
private static void updateFile() {
Socket socket = null;
PrintWriter writer = null;
BufferedInputStream inStream = null;
BufferedOutputStream outStream = null;
try {
String serverName = System.getProperty("server.name");
socket = new Socket(serverName, 80);
writer = new PrintWriter(socket.getOutputStream(), true);
inStream = new BufferedInputStream(socket.getInputStream());
outStream = new BufferedOutputStream(new FileOutputStream(new File("XXX.txt")));
// send an HTTP request
System.out.println("Sending HTTP request to " + serverName);
writer.println("GET /server/source/path/XXX.txt HTTP/1.1");
writer.println("Host: " + serverName + ":80");
writer.println("Connection: Close");
writer.println();
writer.println();
// process response
int len = 0;
byte[] bBuf = new byte[8096];
int count = 0;
while ((len = inStream.read(bBuf)) > 0) {
outStream.write(bBuf, 0, len);
count += len;
}
}
catch (Exception e) {
System.out.println("Error in update(): " + e);
throw new RuntimeException(e.toString());
}
finally {
if (writer != null) {
writer.close();
}
if (outStream != null) {
try { outStream.flush(); outStream.close(); } catch (IOException ignored) {ignored.printStackTrace();}
}
if (inStream != null) {
try { inStream.close(); } catch (IOException ignored) {ignored.printStackTrace();}
}
if (socket != null) {
try { socket.close(); } catch (IOException ignored) {ignored.printStackTrace();}
}
}
}
請提前諮詢以達到此目的,並提前致謝。
不可能直接。如果你嘗試下載一個文件。我建議你使用類似HttpURLConnection的類並使用:connection.getContentLength()來知道要下載的數據的總大小。使用套接字是可能的,但您首先需要內容的標題並獲取「content-length」的值示例 – toto
HTTP中的行終止符是'\ r \ n',而不是'println()'可能給您帶來的任何內容。當內置支持和任意數量的第三方客戶端時,請勿自行實施HTTP。這是不平凡的。有關原因,請參閱RFC 2616。 – EJP