以下方法有时无法捕获数据。我相信这是因为.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);
}
}
答案 0 :(得分: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) {
// ...
}