使用java

时间:2017-07-19 03:44:39

标签: java sockets http

我基本上是尝试使用Java中的Socket进行文件上传(.png文件)。 但在某些时候,执行无限期等待read()返回结果。我不明白这种行为。任何人都可以帮忙吗?

HTML代码

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

    <form action="http://127.0.0.1:8081/upload" method="POST" enctype="multipart/form-data">

        <input type="file" name="file" />
        <button type="submit" name="submit">Upload</button>

    </form>

</body>
</html>

服务器代码:

private void handlePostFileupload(Socket clientSocket, int contentLength)
        throws IOException {

    InputStream is = clientSocket.getInputStream();
    OutputStream os = new FileOutputStream(new File("/home/renju/opt/WS1/SocketProgrammingTests/upload/file_"+System.currentTimeMillis()+".png"));

    int read = 0;
    byte[] buffer = new byte[1024];
    int totalRead = 0;

    while((read = is.read(buffer)) > 0){

        totalRead += read;
        System.out.println(totalRead);


        os.write(buffer,0,read);
        os.flush();

        System.out.println("Bytes written...");

        if(totalRead == contentLength){
            System.out.println("Completed uploading....");
            break;
        }
    }

    os.close();


    OutputStream clientOS = clientSocket.getOutputStream();

    StringBuilder sb = new StringBuilder();

    sb.append("HTTP/1.1 200 OK ").append("\r\n").append("\r\n")
            .append("<TITLE>").append("SUCCESS").append("</TITLE>");

    String response = sb.toString();

    clientOS.write(response.getBytes("UTF-8"));

    clientOS.close();

    clientSocket.close();


}

clinetSocket: = serverSocket.accept(); contentLength = valueOf(“Content-Length”);

HTTP消息:

POST /upload HTTP/1.1
Host: 127.0.0.1:8081
Connection: keep-alive
Content-Length: 511715
Cache-Control: max-age=0
Origin: null
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryodqUZ1SAXEBUXSd9
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8

控制台O / P(部分,朝向结束):

Bytes written...
491520
Bytes written...
492544
Bytes written...
493568
Bytes written...
494592
Bytes written...
495333
Bytes written...

0 个答案:

没有答案