A bug in a small program with real-time feedback on upload speed
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- // TODO Auto-generated method stub
- int LENGTH=10240;
- InputStream is=request.getInputStream();
- String fn=UUID.randomUUID().toString();
- File a=new File(HlsConfigure.getPath()+fn);
- byte []content=new byte[LENGTH];
- int length;
- OutputStream os =new FileOutputStream(a);
- PrintWriter out = response.getWriter();
- out.write("
- long total=0;
- long vb=System.currentTimeMillis();
- again:
- while(true){
- int total_length=0;
- long begin=System.currentTimeMillis();
- while((length=is.read(content))!=-1){
- os.write(content, 0, length);
- System.out.println("get "+length);
- total_length+=length;
- if(total_length>=200*1024){
- break;
- }
- }
- System.out.println("will write speed");
- long time=System.currentTimeMillis()-begin;
- out.write("<tr><td>");
- out.write(Integer.toString(total_length));
- out.write("</td><td>");
- out.write(Double.toString(total_length/(1.0240)/(time)));
- out.write("</td></tr>");
- total+=total_length;
- out.flush();
- if(length==-1)
- break;
- }
- os.close();
- long time=System.currentTimeMillis()-vb;
- out.write("<tr><td>");
- out.write(Long.toString(total));
- out.write("</td><td>");
- String speed=Double.toString(total/(1.0240)/(time));
- out.write(speed);
- out.write("</td></tr>");
- out.flush();
- out.write("</table></body>
- System.out.println("from "+request.getRemoteAddr()+ " speed is "+speed);
- // a.delete();
- }
The code is simple:
1. Open inputstream, read the stream, and write it to the file;
2. Feedback on the upload speed per K;
3. The client segment uses the simplest input type = 'file' to upload files;
However, when the customer uploads a large file, the hang will not be completed.
The reason is:
1. When the Browser fails to send the request, it will not read the server output. The idea of displaying the upload speed in real time is incorrect;
2. From the code execution logic, the client segment uploads and the service segment receives data, which does not cause the server buffer to be full;
3. However, the data returned by the server to the customer segment is not read from the buffer zone due to the reason of 1. Therefore, the buffer of the customer segment will be full;
4. As a result, 28 rows of write cannot be written;
5. Because the server is blocked in the write field, the server will not read any more data.
6. The server's buffer zone is full, so the client's upload will be hung.
Note:
ACK packets are implemented by the tcp protocol stack. Therefore, ACK is not affected regardless of whether the program reads the data in the buffer zone. If not all data is written, the window value will decrease. This flag can be used to indicate whether the program has not read data;