import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class HttpServer {
public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "src\\main\\java\\ex01\\static";
public static void main(String[] args) throws IOException, InterruptedException {
HttpServer server = new HttpServer();
server.await();
}
public void await(){
ServerSocket serverSocket = null;
int port = 8999;
try{
serverSocket = new ServerSocket(port,1, InetAddress.getByName("127.0.0.1"));
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
Socket socket = null;
try {
socket = serverSocket.accept();
} catch (IOException e) {
e.printStackTrace();
}
PrintWriter printWriter = null;
try {
printWriter = new PrintWriter(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
String errorMessage = "HTTP/1.1 404 File Not Found\r\n"+
"Content-Type: text/html\r\n" +
"Content-Length: 23\r\n" +"\n"+
"<h1>File Not Found</h1>";
printWriter.println(errorMessage);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
我在浏览器访问http://127.0.0.1:8999/home
却无法访问。
输出为:
Connected to the target VM, address: '127.0.0.1:49586', transport: 'socket'
Disconnected from the target VM, address: '127.0.0.1:49586', transport: 'socket'