学习tomcat能理解web开发。
基础储备知识
http协议定义了网络传输内容格式
HTTP请求
一个HTTP请求包括三个组成部分:
方法—统一资源标识符(URI)—协议/版本
请求的头部
主体内容
下面是一个HTTP请求的例子:
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
HTTP响应
类似于HTTP请求,一个HTTP响应也包括三个组成部分:
方法—统一资源标识符(URI)—协议/版本
响应的头部
主体内容
下面是一个HTTP响应的例子:
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>
java网络
套接字是网络连接的一个端点。套接字使得一个应用可以从网络中读取和写入数据。
放在两个不同计算机上的两个应用可以通过连接发送和接受字节流。
java.net.Socket
要创建一个套接字,你可以使用Socket类众多构造方法中的一个。
其中一个接收主机名称和端口号:
public Socket (java.lang.String host, int port)
java.net.SocketServer
Socket类代表一个客户端套接字。
public ServerSocket(int port, int backLog, InetAddress bindingAddress);
backLog代表接请求的最大队列长度
InetAddress监听网址
例子
new ServerSocket(8080, 1, InetAddress.getByName("127.0.0.1"));
一个简单服务器的例子
public void await() {
ServerSocket serverSocket = null;
int port = 8080;
try {
serverSocket = new ServerSocket(port, 1,InetAddress.getByName("127.0.0.1"));
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
} // Loop waiting for a request
while (!shutdown) {
Socket socket = null;
InputStream input = null;
OutputStream output = null;
try {
socket = serverSocket.accept();
input = socket.getInputStream();
output = socket.getOutputStream();
// create Request object and parse Request
request = new Request(input);
request.parse();
// create Response object Response
response = new Response(output);
response.setRequest(request);
response.sendStaticResource();
// Close the socket
socket.close();
//check if the previous URI is a shutdown command
shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
} catch (Exception e) {
e.printStackTrace (); continue;
}
}
}