1
我有Java套接字的另一個問題。服務器的套接字不會像應該那樣解釋請求。我認爲讀取HTML標題後的行有問題,但我不知道這段代碼有什麼問題。 TIA。閱讀請求暫停服務器
這裏的代碼片段:
@Override
public void run() {
DataOutputStream dout = null;
BufferedReader reader = null;
try {
dout = new DataOutputStream(socket.getOutputStream());
reader = new BufferedReader(
new InputStreamReader(
socket.getInputStream(), UTF-8"));
String requestString = reader.readLine();
StringTokenizer tokenizer = new StringTokenizer(requestString);
String httpMethod = tokenizer.nextToken();
String httpQueryString = tokenizer.nextToken();
System.out.println("method: " + httpMethod);
System.out.println("query: " + httpQueryString);
String line;
int i = 0;
while (! (line = reader.readLine())
.equals("")) {
System.out.println(i++ + " : " + line);
}
//DEBUG
System.out.println("foo");
// HERE IS THE PROBLEM !!!
line = reader.readLine();
System.out.println("aaa " + line);
line = reader.readLine();
System.out.println("bbb " + line);
line = reader.readLine();
System.out.println("ccc " + line);
// Pseudocode
if (GET) {
if ("/") {
...
} else if (isFile) {
...
} else {
...
}
} else if (POST) {
... //TODO
} else {
Error 404
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//Cleaning
try {
reader.close();
dout.close();
socket.close();
} catch (IOException e) {
Logger.getAnonymousLogger().warning("Socket cannot be closed");
}
}
}
和輸出我得到:
INFO: Server is RUNNING
INFO: Connection accepted
method: GET
query:/
0 : Host: 127.0.0.1:8001
1 : User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0
2 : Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
3 : Accept-Language: pl,en-us;q=0.7,en;q=0.3
4 : Accept-Encoding: gzip, deflate
5 : DNT: 1
6 : Connection: keep-alive
7 : Cache-Control: max-age=0
foo
--- in this place server halts ---
--- then I refresh page or do anything else that sends request (GET, POST) ---
--- and server receives 'remaining' part of the request ---
aaa null // in POST this line has send values
bbb null
ccc null
INFO: method = GET
INFO: Connection accepted
method: GET
query:/
0 : Host: 127.0.0.1:8001
1 : User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0
2 : Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
3 : Accept-Language: pl,en-us;q=0.7,en;q=0.3
4 : Accept-Encoding: gzip, deflate
5 : DNT: 1
6 : Connection: keep-alive
foo
--- in this place server halts ---
--- then I refresh page or do anything else that sends request (GET, POST) ---
--- and server receives 'remaining' part of the request ---
是的,但我該如何解決這個問題?應該是: 1.接收來自客戶端的請求。 2.回答此請求。 3.接收剩餘部分。 4.做些什麼。 ? – Miki
請勿自行實施HTTP服務器。使用servlet或其他東西。 – irreputable
我必須。這是編程課的一個項目。 我想,如果我想要得到其餘的標題(或POST消息體),我必須發送響應「200 OK」。但是,那麼,我怎樣才能發回帶有搜索結果的頁面呢? – Miki