JAVA 模拟TomCat服务器

2018-01-26 10:38:42来源:网络收集作者:咖啡不加糖人点击

分享

[var1]

一、模拟TomCat服务器


public class HttpServer{
//服务器返回数据必要的数据头
private static String head = "HTTP/1.1 200 OK"
+"Connection: close"
+"/n/n";
public static void main(String[] args)throws IOExecption{
System.out.println("服务器启动");
//端口: 80为默认端口,请求时可以省略不写
ServerSocket socket = new ServerSocket(8081);
//等待浏览器请求
Socket brower = socket.accept();
//一次性读取浏览器请求发来的请求头,避免阻塞
InputStream receiver = brower.getInputStream();
byte[] buf = new byte[1024];
int len = receiver.read(buf);
System.out.println(new String(buf,0,len));
//如何给浏览器返回信息
OutputStream sender = brower.getOutputStream();
//html功能: 通过浏览器请求的路径,解析具体路径下的文件,转换成html的字符串
String html = "Request Success";
String msg = head+html;
sender.write(msg.getBytes());
//服务关闭
brower.close();
socket.close();
}
}

浏览器发来的信息
连接状态 (注: 和HTTP协议相关)
Connection: keep-alive
用户代理
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
请求次数
Upgrade-Insecure-Requests: 1
支持的格式
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8
浏览器支持的压缩方式
Accept-Encoding: gzip, deflate, br
支持的语言
Accept-Language: zh-CN,zh;q=0.9
结束标记
/n/n


二、模拟客户端浏览器


public class HttpClient{
private static String head = "GET /Test/index.html HTTP/1.1/n"
+"Host: localhost:8080/n"
+"Connection: close/n"
+"/n";
public static void main(String[] args) throws UnknownHostException, IOEXception{
System.out.println("Brower request message...");
Socket brower = new Socket("localhost",8080);
PrintWriter sender = new PrintWriter(brower.getOutputStream(),true);
// 模拟浏览器发送请求头信息
sender.println(head);
// 接收tomcat返回的信息
BufferedReader receiver = new BufferedReader(new InputStreamReader(brower.getInputStream()));
String line = null;
while((line = receiver.readLine())!=null){
System.out.println(line);
}
brower.close();
}
}

HTTP 协议版本 : 状态码
HTTP/1.1 200 OK
服务的提供
Server: Apache-Coyote/1.1
支持的范围
Accept-Ranges: bytes
标记(token)
ETag: W/”304-1516331676000”
最后的修改时间
Last-Modified: Fri, 19 Jan 2018 03:14:36 GMT
返回的文本格式
Content-Type: text/html
返回的内容文本长度
Content-Length: 304
返回的时间
Date: Fri, 19 Jan 2018 06:39:47 GMT
连接方式
Connection: close
结束标识
/n


微信扫一扫

第七城市微信公众平台