简单的Web服务器
本章介绍Java Web服务器是如何运行的
Warming Up
因为使用HTTP与客户(浏览器)通信
so
- Web服务器 == Http服务器
- 两个重要的类 java.net.Socket 和 java.net.ServerSocket
本章内容
- 简介HTTP
- 介绍一个简单的Web服务器
HTTP
HyperText Transfer Protocol 超文本传输协议
HTTP请求
- 请求方法 URL 协议/版本
- 请求头
- 回车换行
- 实体
举例如下
POST /examples/default.jsp HTTP/1.1
Accept: text/plain; text/html
Accept-Language: en-gb
Connection: Keep-Alive
Host: localhost
User-Agent: Mozilla/4.0 (compatible; MSIE 4.01; Windows 98)
Content-Length: 33
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
lastName=Franks&firstName=Michael
HTTP响应
与HTTP请求类似
- 协议 状态码 描述
- 响应头
- 回车换行CRLF
- 响应实体段
HTTP/1.1 200 OK
Server: Microsoft-IIS/4.0
Date: Mon, 5 Jan 2004 13:13:33 GMT
Content-Type: text/html
Last-Modified: Mon, 5 Jan 2004 13:13:12 GMT
Content-Length: 112
<html>
<head>
<title>HTTP Response Example</title>
</head>
<body>
Welcome to Brainy Software
</body>
</html>
Socket类
套接字 java.net.Socket
网络连接的端点 –> 网络 I/O 通过Socket在网络中读、写数据 就好比电话
创建
拿起电话打给哪儿
public Socket (java.lang.String host , int port )
//打给yahoo80端口
new Socket("yahoo", 80);
读
听筒
java.io.InputStream getInputStream()
写
话筒
//字节流
getOutputStream()
//字符流
返回的OutputStream对象创建PrintWriter对象
OutputStream os = socket.getOutputStream();
boolean autoflush = true;
PrintWriter out = new PrintWriter(socket.getOutputStream(), autoflush);
实例
创建了一个套接字Socket,用于本地HTTP服务器通信,发送HTTP请求 接受服务器响应信息 并将其输出在console
//创建socket
Socket socket = new Socket("127.0.0.1", "8080");
//创建发送字节流
OutputStream os = socket.getOutputStream();
boolean autoflush = true;
PrintWriter out = new PrintWriter(socket.getOutputStream(), autoflush);
//缓冲
BufferedReader in = new BufferedReader(new InputStreamReader( socket.getInputstream() ));
// send an HTTP request to the web server
out.println("GET /index.jsp HTTP/1.1");
out.println("Host: localhost:8080");
out.println("Connection: Close");
out.println();
// read the response
boolean loop = true;
StringBuffer sb = new StringBuffer(8096);
while (loop) {
if ( in.ready() ) {
int i=0;
while (i!=-1) {
i = in.read();
sb.append((char) i);
}
loop = false;
}
Thread.currentThread().sleep(50);
}
// display the response to the out console
System.out.println(sb.toString());
socket.close();
ServerSocket类 客户端套接字
即客户要连接到远程服务器应用程序时创建的套接字
serverSocket与Socket不同
SeverSocket要等客户端的连接请求
服务器接收到请求 创建一个Socket实例来处理与客户的通信
构造
ServerSocket(int port, int backlog, InetAddress bindAddr) //listen backlog?
//表示在服务器拒绝接收传入的请求之前,传入连接请求的最大队列长度
其中静态绑定地址必须是java.net.InetAddress
创建方法可以是 InetAddress.getByName("127.0.0.1");
new ServerSocket(8080, 1, InetAddress.getByName("127.0.0.1"));
创建后等待传入连接请求,连接请求通过服务器套接字 侦听的端口绑定传入
这些工作通过ServerSocket类的accept方法完成
此方法为阻塞方法
APPLICATION
实现
- 入口点main方法在httpServer中
- 创建HttpServer对象
- 调用await方法
- 创建客户端套接字ServerSocket
- 阻塞方法accept
- Request 读入解析
- Response 发送静态资源