代码如下(网上参考而来):
访问:http://localhost:8888/即可。
注意:
测试时发现,需要在run方法里面设上断点才能正常访问到页面。
- import java.io.IOException;
- import java.io.PrintStream;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.net.UnknownHostException;
- import java.util.Date;
- public class HttpServlet implements Runnable {
- ServerSocket server;
- public HttpServlet() throws UnknownHostException, IOException {
- server = new ServerSocket(8888);
- }
- public static void main(String[] args) throws Exception {
- Thread t = new Thread(new HttpServlet());
- t.start();
- }
- public void run() {
- boolean listening = true;
- while (listening) {
- try {
- Socket client = server.accept();
- System.out.println("client:" + client);
- PrintStream out = new PrintStream(client.getOutputStream(), true);
- String content = "<h1>It works.<h1>/r/n";
- out.print("HTTP/1.0 202 OK" + "/r/n");
- out.print("Server: testserver" + "/r/n");
- out.print("Date: " + new Date() + "/r/n");
- out.print("Content-length: " + content.length() + "/r/n");
- out.print("Content-type: text/html" + "/r/n");
- out.print("/r/n");
- out.print(content);
- out.flush();
- out.close();
- client.close();
- } catch (Exception ex) {
- System.out.println(ex.getMessage());
- }
- }
- if (server != null) {
- try {
- server.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
注意:
测试时发现,需要在run方法里面设上断点才能正常访问到页面。