我正在编写一个在浏览器中输出请求编号的Java Server。它是一个多线程应用程序,假设为每个请求创建一个新线程并输出下一个数字。它确实有效,但是当我只有一个增量时,数字输出增加4。所以我有一种感觉,服务器不知何故继续接收请求而不在浏览器中输出它们。
public class ResponseServer {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int clientNum = 0;
ServerSocket serverSocket = new ServerSocket(8000);
Socket socket = null;
while (true) {
socket = serverSocket.accept();
System.out.println("CLIENT NUM " + clientNum);
new HandleClient(socket, clientNum++).run();
System.out.println("DONE");
}
}
static class HandleClient implements Runnable {
Socket socket;
int counter;
public HandleClient(Socket socket, int counter) {
System.out.println("RECIEVED " + counter);
this.socket = socket;
this.counter = counter;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
InputStream in = socket.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in));
OutputStream out = socket.getOutputStream();
String response = "<h2>" + counter + "</h2>";
out.write("HTTP/1.1 200 OK\n".getBytes());
out.write("Content-Type: text/html; charset=utf-8\n".getBytes());
out.write(("Content-Length: " + response.length() + "\n\n").getBytes());
out.write(response.getBytes());
out.flush();
out.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
}
答案 0 :(得分:0)
Chrome和IE浏览器中存在错误。代码没有问题 - 如果您使用Firefox
,则有效