-3

以下方法有时不会捕获数据。我相信这是因为 .ready() 功能。

我们已经通过睡眠破解了它,但我认为这不是充分的证据,而且似乎是一个糟糕的破解。

您能否就如何修复此方法提出建议,以便在完全读取请求时它可以工作?

提前致谢

/**
     * Parses a client request and calls the appropriate handler
     * @throws Exception
     */
    private void processClientRequest() throws Exception{
            Socket connectedClient = null;
        BufferedReader clientRequest = new BufferedReader(new InputStreamReader(connectedClient.getInputStream()));

        System.out.println(clientRequest);
        String requestString = clientRequest.readLine();

        String header = requestString;

        //Break up request
        StringTokenizer tokenizer = new StringTokenizer(header);

        //Different request parts
        String httpMethod = tokenizer.nextToken();
        String httpQueryString = tokenizer.nextToken();

        //Print client request
        StringBuffer responseBuffer = new StringBuffer();

        //Sleep to bypass weird clientRequest.ready() error
        if (httpMethod.equals("POST")) {
            Thread.sleep(100);
        }

        while (clientRequest.ready()) {
            responseBuffer.append(requestString + " ");
            System.out.println(requestString);

            requestString = clientRequest.readLine();
        }

        //Process GET request
        if (httpMethod.equals("GET")) {
            processGETRequests(httpQueryString, requestString);


        }else if (httpMethod.equals("POST")) {
            processPOSTRequests(responseBuffer, httpQueryString);
        }
    }
4

1 回答 1

3

当您使用字符串时,您必须始终同意编码并且永远不要使用默认值。在你的

// use wathever charset encoding you know is pressent on the socket stream like UTF-8
new InputStreamReader(socket.getInputStream(), "US-ASCII") 

您不需要调用 ready 方法,方法 readLine() 将阻塞,直到有新行要读取。你的时间应该是

while ((requestString = clientRequest.readLine()) != null) {
    // ...
}
于 2013-07-08T21:35:54.577 回答