我正在编写网络服务器:
import java.net.ServerSocket;
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class HttpServer {
public static void main(String[] args) throws Throwable {
//http://localhost:3000
ServerSocket ss = new ServerSocket(3000);
while (true) {
//Waiting for socket
Socket s = ss.accept();
System.out.println("Client accepted");
//The main process
new SocketProcessor(s, ss).start();
}
}
private static class SocketProcessor implements Runnable {
private Thread t;
private Socket s;
private InputStream is;
private OutputStream os;
private SocketProcessor(Socket s, ServerSocket ss) throws Throwable {
t = new Thread(this, "Server Thread");
this.s = s;
this.is = s.getInputStream();
this.os = s.getOutputStream();
}
public void run() {
try {
readInputHeaders();
writeResponse("<html><body><h1>Hello</h1></body></html>");
} catch (Throwable t) {
/*do nothing*/
} finally {
try {
s.close();
} catch (Throwable t) {
}
}
System.out.println("Client processing finished");
}
public void start() {
t.start();
}
private void writeResponse(String s) throws Throwable {
String response = "HTTP/1.1 200 OK\r\n" +
"Server: Server\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: " + s.length() + "\r\n" +
"Connection: close\r\n\r\n";
String result = response + s;
os.write(result.getBytes());
os.flush();
}
private void readInputHeaders() throws Throwable {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while (true) {
int a = br.read();
System.out.print((char)a);
if (a==-1) {
break;
}
}
}
}
}
但我读书时遇到了麻烦。这种方法需要花费太多时间:
private void readInputHeaders() throws Throwable {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while (true) {
int a = br.read();
System.out.print((char)a);
if (a==-1) {
break;
}
}
}
它返回标题和查询字符串,但它会冻结我的网络服务器。怎么了?
答案 0 :(得分:1)
您需要阅读并实施HTTP协议,您需要为其阅读RFC。像这样的猜测是行不通的。您收集请求的方法并没有开始有效。 EOS不能跟随请求,否则您无法写入响应。您需要查看内容长度标题,分块编码等。