0

我正在开发一个服务器,它应该能够立即接收多个文件,并能够将它们保存到本地硬盘驱动器。收到文件后,服​​务器应向客户端发送响应并确认文件已通过。当我尝试立即发送多个文件时,结果是 1 个客户端收到了第二个客户端的答案,反之亦然。
有没有人知道这台服务器有什么问题?

这是我的servlet代码:

protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {

    try {
        request.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }
    response.setCharacterEncoding("UTF-8");
    PrintWriter writer = null;
    try {
        writer = response.getWriter();
    } catch (IOException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }
    try {
        // get access to file that is uploaded from client
        Part p1 = request.getPart("File");
        InputStream is = p1.getInputStream();

        // read filename which is sent as a part
        Part p2  = request.getPart("MetaData");
        Scanner s = new Scanner(p2.getInputStream());
        String stringJson = s.nextLine();    // read filename from stream
        s.close();

        json = new JSONObject(stringJson);
        fileName = new String(json.getString("FileName").getBytes("UTF-8"));
        fileDirectory = BASE + request.getSession().getId();
        File dir = new File(fileDirectory);
        dir.mkdir();
        // get filename to use on the server
        String outputfile = BASE + dir.getName() + "/" + fileName;  // get path on the server
        FileOutputStream os = new FileOutputStream (outputfile);

        // write bytes taken from uploaded file to target file
        byte[] buffer = new byte[1024];
        int ch = is.read(buffer);
        final Object lock = new Object();
        while (ch != -1) { 
            synchronized (lock) {
                os.write(buffer);
                ch = is.read(buffer);
            }
        }
        os.close();
        is.close();
    }
    catch(Exception ex) {
        writer.println("Exception -->" + ex.getMessage());
    }
    finally { 
        try {
            myRequest = request;
            try {
                printFile(request.getSession().getId(), writer);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                writer.println("Exception -->" + e.getMessage());
            }
            writer.close();
        } catch (InterruptedException e) {
            writer.println("Exception -->" + e.getMessage());
        }
    }               


}



提前致谢 :)

4

0 回答 0