使用socket通信原理实现简单的http协议,代码很简单
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
ServerSocket serverSocket; // 791202.com public Tomcat(int port) { try { serverSocket = new ServerSocket(port); System.out.println("服务端启动成功,端口是:" + port); } catch (IOException e) { e.printStackTrace(); } } public void start() { while (true) { try { Socket accept = serverSocket.accept(); InputStream inputStream = accept.getInputStream(); byte[] buff = new byte[1024]; int len = inputStream.read(buff); if (len > 0) { String msg = new String(buff, 0, len); System.out.println("接收到数据:" + msg); } OutputStream outputStream = accept.getOutputStream(); StringBuilder resp = new StringBuilder(); resp.append("HTTP/1.1\n"); resp.append("Content-type:text/html\n\n"); resp.append("<h1>Hello Tomcat!</h1>"); byte[] bytes = resp.toString().getBytes(); outputStream.write(bytes); outputStream.flush(); outputStream.close(); } catch (Exception ex) { } } } public static void main(String[] args) { Tomcat tomcat = new Tomcat(8080); tomcat.start(); } |
启动后访问自己的tomcat:http://localhost:8080/, 返回结果如下:
0