动手实现自己的http服务器【精简版】

 1 package v2;
 2 
 3 import java.io.IOException;
 4 import java.io.OutputStream;
 5 import java.io.PrintStream;
 6 import java.io.PrintWriter;
 7 import java.net.ServerSocket;
 8 import java.net.Socket;
 9 import java.util.List;
10 import java.util.Scanner;
11 
12 public class Test
13 {
14   public static void main(String[] args)
15   {
16     try
17     {
18       Socket s = null;
19       ServerSocket ss = new ServerSocket(80);
20       while ((s = ss.accept()) != null)
21       {
22         Scanner input = new Scanner(s.getInputStream(), "utf-8");
23         int c = 0;
24         String tmp = null;
25         while (input.hasNextLine())
26         {
27           tmp = input.nextLine();
28           if (tmp.trim().length() == 0) {
29             break;
30           }
31           System.out.println(c + "·····································" + tmp);
32           c++;
33         }
34         System.out.println("开始响应·····························");
35         responseMsg(s, "Hello,world");
36         input.close();
37         s.close();
38       }
39     }
40     catch (IOException e)
41     {
42       e.printStackTrace();
43     }
44   }
45   
46   private static void responseMsg(Socket s, String msg)
47   {
48     try
49     {
50       OutputStream out = s.getOutputStream();
51       PrintWriter pw = new PrintWriter(out);
52       
53       pw.print("HTTP/1.0 500 OK\r\n");
54       pw.print("Content-type:text/html; charset=utf-8\r\n");
55       pw.print("\r\n");
56       
57       pw.println(msg);
58       pw.flush();
59       pw.close();
60     }
61     catch (IOException e)
62     {
63       e.printStackTrace();
64     }
65   }
66   
67   public static void showLines(List<String> lines)
68   {
69     for (String line : lines) {
70       System.out.println(line);
71     }
72   }
73 }
View Code

如果端口被占用了,windows系统可以cmd输入"netstat -ano|find "80"     找到相关进程的id,然后  "taskkill  /f /pid 进程id  "进行查杀

posted @ 2018-02-26 17:30  漫漫人生路总会错几步  阅读(197)  评论(0编辑  收藏  举报