HTTP服务器
http协议的底层是tcp/ip协议,浏览器与服务器的交互就是tcp的通信过程。所以我们可以使用先前学的tcp通讯知识点搭建一个简单的服务器。
思路
- 使用ServerSocket创建一个服务器端(指定端口为8888),阻塞式接受tcp请求(accept()方法)
- 从浏览器访问:http://localhost:8888 就能与服务器端建立连接
- 建立了连接相当于tcp连接建立完成,可以使用Socket client = x.accept() 创建浏览器端的socket
- 创建输入流获取浏览器传入的信息(请求信息)
- 创建输出流返回响应信息,响应信息格式是固定的,一旦写错,浏览器无法接收响应信息
代码
必读注意事项,响应头必须不能写错:
Date:日期 Server:服务器名称等信息 Content-type:text/html Content-length:内容长度,注意就是这一行content-length绝对不能写错,一旦写错,无法返回响应
这里有回车换行符。缺少此回车换行,同样不能返回响应。
package _20191224_server; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Date; public class Server02_again { private ServerSocket serverSocket; public static void main(String[] args) throws IOException { Server02_again server =new Server02_again(); server.start(); } //服务器开启 public void start(){ try { serverSocket = new ServerSocket(8888); receive(); } catch (IOException e) { e.printStackTrace(); } } public void receive() { try { Socket client = serverSocket.accept(); System.out.println("建立了链接"); //接受请求 InputStream is = client.getInputStream(); byte[] datas = new byte[1024*1024]; int len = is.read(datas); String requestInfo = new String(datas,0,len); System.out.println(requestInfo); //发送响应 StringBuilder content = new StringBuilder(); content.append("<html>"); content.append("<head>"); content.append("<title>"); content.append("响应页面"); content.append("</title>"); content.append("</head>"); content.append("<body>"); content.append("我他妈好饿"); content.append("</body>"); content.append("</html>"); int size = content.toString().getBytes().length; StringBuilder responseInfo = new StringBuilder(); String blank = " "; String CRLF = "\r\n"; //响应行:HTTP/1.1 200 OK responseInfo.append("HTTP/1.1").append(blank); responseInfo.append(200).append(blank); responseInfo.append("OK").append(CRLF); //响应头 /*Date:new Date() *Server:xiaohei Server/0.0.1;charset=GBK *Content-type:text/html *Contetn-length:454534 */ /* *响应头写错一个字都不对,都不会正确返回响应 */ responseInfo.append("Date:").append(new Date()).append(CRLF); responseInfo.append("Server:").append("xiaohei Server/0.0.1;charset=GBK").append(CRLF); responseInfo.append("Contetn-type:text/html").append(CRLF); responseInfo.append("Content-length:").append(size).append(CRLF); responseInfo.append(CRLF); //发出去 responseInfo.append(content.toString());//注意转为string // BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream())); bw.write(responseInfo.toString()); bw.flush(); }catch (IOException e) { e.printStackTrace(); System.out.println("客户端错误"); } } public void stop() { } }