現在httpサーバーを作成していますが、ソケットからの読み取りに問題があります。私の問題はinputStream
、クライアントからの送信が終了せず、クライアントが閉じられるまで読み取りを続けることです。httpリクエストを送信した直後に、クライアントがサーバーとの接続を閉じないことを知っています。while loop
クライアントがすべてのリクエストデータ(つまり、ヘッダー+本文)を送信し たときに終了するにはどうすればよいですか。
while (in.hasNextLine()) {
String line = in.nextLine();
if (line.equals("")){ // last line of request header is blank
break; // quit while loop when last line of header is reached
} else {
request = request + line + "\n";
}
}
皆さんからのコメントと回答を読んだ後、これが私が思いついたものです、
is = incoming.getInputStream();
os = incoming.getOutputStream();
in = new Scanner(is);
out = new DataOutputStream(os);
RequestHandler rh = new RequestHandler();
int length = 0;
while (in.hasNextLine()) {
String line = in.nextLine();
if (line.equals("")) { // last line of request message
// header is a
// blank line
break; // quit while loop when last line of header is
// reached
}
if (line.startsWith("Content-Length: ")) { // get the
// content-length
int index = line.indexOf(':') + 1;
String len = line.substring(index).trim();
length = Integer.parseInt(len);
}
request = request + line + "\n";
}
byte[] body = new byte[length];
int i = 0;
while (i < length) {
byte b = in.nextByte();
body[i] = b;
i++;
}
しかし、私はまだバイト単位の読み取りについては理解していません。-1まで読み取るコードを記述できますが、EOFがなく、クライアントが接続を閉じていない場合でもスタックします。