Java手写服务器(一)
客户端在浏览器发送请求,服务器接收请求,并作出响应。
a.html
<html> <head> <title>表单</title> </head> <body> <form method="GET" action="http://localhost:8870/index.html"> 用户名:<input type="text"name="uname"id="name"> 密码:<input type="password"name="pws"id="pass"> <input type="submit" value="登录"> </form> </body> </html>
Server3.java
package cn.server; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Date; /* * 创建服务器,并启动 * 请求并响应 */ public class Server3 { private ServerSocket server; public static final String CRLF="\r\n"; public static final String BLANK=" "; public static void main(String[] args) { Server3 server=new Server3(); server.start(); } //启动方法 public void start() { try { server = new ServerSocket(8870); this.receive(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* * 接收客户端 */ private void receive() { try { Socket client=server.accept(); String msg=null; byte[] data=new byte[20480]; int len=client.getInputStream().read(data); //接收客户端的请求信息 String requestInfo=new String(data,0,len).trim(); System.out.println(requestInfo); //响应 StringBuilder responseContext=new StringBuilder(); responseContext.append("<html>\r\n" + " <head>\r\n" + " <title>表单</title>\r\n" + " </head>\r\n" + " <body>\r\n" + " <form method=\"GET\" action=\"http://localhost:8880/index.html\">\r\n" + " sun:<input type=\"text\"name=\"uname\"id=\"name\">\r\n" + " pwd:<input type=\"password\"name=\"pws\"id=\"pass\">\r\n" + " <input type=\"submit\" value=\"登录\">\r\n" + " </form>\r\n" + " </body>\r\n" + "</html>"); StringBuilder response=new StringBuilder(); //1)http协议版本、状态代码 、描述 response.append("HTTP/1.1").append(BLANK).append("200").append(BLANK).append("ok").append(CRLF); //2)响应头(response Head) response.append("sun").append(CRLF); response.append("Date").append(new Date()).append(CRLF); response.append("Content-type:text/html;charset=GBK").append(CRLF); //正文的长度 :字节长度 response.append("Content-Length:").append(responseContext.toString().getBytes().length).append(CRLF); //3)正文之前 response.append(CRLF); //4)正文 response.append(responseContext); //输出流 将响应发送出去 BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(client.getOutputStream())); bw.write(response.toString()); bw.flush(); bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* * 停止服务器 */ public void stop() { } }
服务器打印结束过来的请求
响应结果