一直以來都是用Java寫Web,但是呢,還沒好好去了解實現(xiàn)一個Web Server寞奸,由此開始要逐步寫出一個完善的WebServer,努力實現(xiàn)高性能的Web站點在跳。
一颂砸、什么是Web服務(wù)器##
網(wǎng)頁服務(wù)器(Web server)一詞有兩個意思:
一臺負(fù)責(zé)提供網(wǎng)頁的電腦蠢壹,主要是各種編程語言構(gòu)建而成牵舱,通過HTTP協(xié)議傳給客戶端(一般是指網(wǎng)頁瀏覽器)仰税。
一個提供網(wǎng)頁的服務(wù)器程序。
雖然每個網(wǎng)頁服務(wù)器程序有很多不同割坠,但有一些共同的特點:每一個網(wǎng)頁服務(wù)器程序都需要從網(wǎng)絡(luò)接受HTTP request齐帚,然后提供HTTP response給請求者。HTTP回復(fù)一般包含一個HTML文件韭脊,有時也可以包含純文本文件童谒、圖像或其他類型的文件。
二沪羔、HTTP協(xié)議##
-
簡介
HTTP是一個屬于應(yīng)用層的面向?qū)ο蟮膮f(xié)議饥伊,由于其簡捷、快速的方式蔫饰,適用于分布式超媒體信息系統(tǒng)琅豆。它于1990年提出,經(jīng)過幾年的使用與發(fā)展篓吁,得到不斷地完善和擴展茫因。目前在WWW中使用的是HTTP/1.0的第六版,HTTP/1.1的規(guī)范化工作正在進行之中杖剪,而且HTTP-NG(Next Generation of HTTP)的建議已經(jīng)提出冻押。
HTTP協(xié)議的主要特點可概括如下:
1.支持客戶/服務(wù)器模式。
2.簡單快速:客戶向服務(wù)器請求服務(wù)時盛嘿,只需傳送請求方法和路徑洛巢。請求方法常用的有GET、HEAD次兆、POST稿茉。每種方法規(guī)定了客戶與服務(wù)器聯(lián)系的類型不同。由于HTTP協(xié)議簡單,使得HTTP服務(wù)器的程序規(guī)模小漓库,因而通信速度很快恃慧。
3.靈活:HTTP允許傳輸任意類型的數(shù)據(jù)對象。正在傳輸?shù)念愋陀蒀ontent-Type加以標(biāo)記渺蒿。
4.無連接:無連接的含義是限制每次連接只處理一個請求痢士。服務(wù)器處理完客戶的請求,并收到客戶的應(yīng)答后蘸嘶,即斷開連接良瞧。采用這種方式可以節(jié)省傳輸時間。
5.無狀態(tài):HTTP協(xié)議是無狀態(tài)協(xié)議训唱。無狀態(tài)是指協(xié)議對于事務(wù)處理沒有記憶能力。缺少狀態(tài)意味著如果后續(xù)處理需要前面的信息挚冤,則它必須重傳况增,這樣可能導(dǎo)致每次連接傳送的數(shù)據(jù)量增大。另一方面训挡,在服務(wù)器不需要先前信息時它的應(yīng)答就較快澳骤。
-
HTTP協(xié)議詳解-請求
http請求由三部分組成,分別是:請求行澜薄、消息報頭为肮、請求正文
1、請求行以一個方法符號開頭肤京,以空格分開颊艳,后面跟著請求的URI和協(xié)議的版本,格式如下:Method Request-URI HTTP-Version CRLF
其中 Method表示請求方法忘分;Request-URI是一個統(tǒng)一資源標(biāo)識符棋枕;HTTP-Version表示請求的HTTP協(xié)議版本;CRLF表示回車和換行(除了作為結(jié)尾的CRLF外妒峦,不允許出現(xiàn)單獨的CR或LF字符)重斑。
請求方法(所有方法全為大寫)有多種,各個方法的解釋如下:
GET 請求獲取Request-URI所標(biāo)識的資源
POST 在Request-URI所標(biāo)識的資源后附加新的數(shù)據(jù)
HEAD 請求獲取由Request-URI所標(biāo)識的資源的響應(yīng)消息報頭
PUT 請求服務(wù)器存儲一個資源肯骇,并用Request-URI作為其標(biāo)識
DELETE 請求服務(wù)器刪除Request-URI所標(biāo)識的資源
TRACE 請求服務(wù)器回送收到的請求信息窥浪,主要用于測試或診斷
CONNECT 保留將來使用
OPTIONS 請求查詢服務(wù)器的性能,或者查詢與資源相關(guān)的選項和需求
應(yīng)用舉例:
GET方法:在瀏覽器的地址欄中輸入網(wǎng)址的方式訪問網(wǎng)頁時笛丙,瀏覽器采用GET方法向服務(wù)器獲取資源漾脂,eg:GET /form.html HTTP/1.1 (CRLF)
POST方法要求被請求服務(wù)器接受附在請求后面的數(shù)據(jù),常用于提交表單若债。
eg:POST /reg.jsp HTTP/ (CRLF)
Accept:image/gif,image/x-xbit,... (CRLF)
...
HOST:www.guet.edu.cn (CRLF)
Content-Length:22 (CRLF)
Connection:Keep-Alive (CRLF)
Cache-Control:no-cache (CRLF)
(CRLF) //該CRLF表示消息報頭已經(jīng)結(jié)束符相,在此之前為消息報頭
user=jeffrey&pwd=1234 //此行以下為提交的數(shù)據(jù)
HEAD方法與GET方法幾乎是一樣的,對于HEAD請求的回應(yīng)部分來說,它的HTTP頭部中包含的信息與通過GET請求所得到的信息是相同的啊终。利用這個方法镜豹,不必傳輸整個資源內(nèi)容,就可以得到Request-URI所標(biāo)識的資源的信息蓝牲。該方法常用于測試超鏈接的有效性趟脂,是否可以訪問,以及最近是否更新例衍。
2昔期、請求報頭后述
3、請求正文(略)
詳情請轉(zhuǎn)到另一篇博文:http://blog.csdn.net/gueter/article/details/1524447
三佛玄、實現(xiàn)自己WebServer
1硼一、實現(xiàn)一個單線程的SingleThreadWebServer
- 首先開啟一個ServerSocket來監(jiān)聽9000端
- 一但獲得一個連接請求,回復(fù)一條信息
public class SingleThreadWebServer implements Runnable{
protected int serverPort = 8080;
protected ServerSocket serverSocket = null;
protected Thread runningThread= null;
public SingleThreadWebServer(int port){
this.serverPort = port;
}
public void run(){
synchronized(this){
this.runningThread = Thread.currentThread();
}
openServerSocket();
System.out.println("Web服務(wù)器開啟了");
while(true){
Socket clientSocket = null;
try {
clientSocket = this.serverSocket.accept();
} catch (IOException e) {
e.printStackTrace();
}
try {
processClientRequest(clientSocket);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void processClientRequest(Socket clientSocket)
throws IOException {
InputStream input = clientSocket.getInputStream();
OutputStream output = clientSocket.getOutputStream();
long time = System.currentTimeMillis();
output.write(("HTTP/1.1 200 OK\n\n<html><body>" +
"木木彬的singleThreadWebServer: " +
time +
"</body></html>").getBytes());
output.close();
input.close();
System.out.println("接收到請求: " + time);
}
private void openServerSocket() {
try {
this.serverSocket = new ServerSocket(this.serverPort);
} catch (IOException e) {
throw new RuntimeException("Cannot open port 8080", e);
}
}
public static void main(String[] args) {
SingleThreadWebServer singleThreadWebServer = new SingleThreadWebServer(9000);
new Thread(singleThreadWebServer).start();
}
}
單線程的WebServer梦抢,接受connection連接和處理請求都在一個線程中般贼,因此一次只能相應(yīng)一個請求
2、實現(xiàn)MultiThreadWebServer
- 首先開啟一個ServerSocket來監(jiān)聽9000端口
- 一單獲得一個連接請求奥吩,把它傳遞給另一個處理線程哼蛆,這樣才能讓你的ServerSocket去接受其它的請求
- 寫一個響應(yīng)。
實現(xiàn)很簡單霞赫,把單線程的processClientRequest函數(shù)改成WorkThread就好
public class MultiThreadWebServer implements Runnable{
protected int serverPort = 8080;
protected ServerSocket serverSocket = null;
protected boolean isStopped = false;
protected Thread runningThread= null;
public MultiThreadWebServer(int port){
this.serverPort = port;
}
public void run(){
synchronized(this){
this.runningThread = Thread.currentThread();
}
openServerSocket();
while(true){
Socket clientSocket = null;
try {
clientSocket = this.serverSocket.accept();
} catch (IOException e) {
e.printStackTrace();
}
new Thread(
new WorkThread(
clientSocket, "mumubin's Multithreaded Server")
).start();
}
}
private void openServerSocket() {
try {
this.serverSocket = new ServerSocket(this.serverPort);
} catch (IOException e) {
throw new RuntimeException("Cannot open port 8080", e);
}
}
public static void main(String[] args) {
MultiThreadWebServer multiThreadWebServer = new MultiThreadWebServer(9090);
new Thread(multiThreadWebServer).start();
}
}
public class WorkThread implements Runnable {
protected Socket clientSocket = null;
protected String serverText = null;
public WorkThread(Socket clientSocket, String serverText) {
this.clientSocket = clientSocket;
this.serverText = serverText;
}
@Override
public void run() {
try {
InputStream inputStream = clientSocket.getInputStream();
OutputStream outputStream = clientSocket.getOutputStream();
long time = System.currentTimeMillis();
outputStream.write(("HTTP/1.1 200 OK\n\nWorkerThread: " +
this.serverText + " - " +
time +
"").getBytes());
inputStream.close();
outputStream.flush();
System.out.println("接收到請求");
outputStream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
但是呢腮介,之前那些,都沒實現(xiàn)HTTP最基本的GET端衰、POST請求叠洗,
3、實現(xiàn)Post靴迫、Get方法
流程如下:
- 首先開啟一個ServerSocket來監(jiān)聽10000端口
- 一單獲得一個連接請求惕味,把它傳遞給另一個處理線程,這樣才能讓你的ServerSocket去接受其它的請求
- 解析請求玉锌,看它是GET還是POST名挥,還有傳遞過來的參數(shù)
- 根據(jù)相應(yīng)的請求寫一個響應(yīng)。
接下來我們先看下其實現(xiàn)代碼
InputStream inputStream = clientSocket.getInputStream();
InputStream input = clientSocket.getInputStream();
byte[] byteBuffer = new byte[1000];
do{
input.read(byteBuffer);
for (byte a :byteBuffer)
System.out.print((char)a);
}
while (input.read() != -1);
Request的具體信息
GET / HTTP/1.1
Host: 127.0.0.1:9090
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: zh-CN,zh;q=0.8
Cookie: _ga=GA1.1.413734972.1430379491
因此通過解析Request就可以構(gòu)建doPost和doGet方法,修改后的WorkThread
public class WorkThread implements Runnable {
protected Socket clientSocket = null;
protected String serverText = null;
public WorkThread(Socket clientSocket, String serverText) {
this.clientSocket = clientSocket;
this.serverText = serverText;
}
public void doPost()
{
try {
OutputStream outputStream = clientSocket.getOutputStream();
outputStream.write(("HTTP/1.1 200 OK\n\nWorkerThread: " +
"this is by post").getBytes());
outputStream.flush();
outputStream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void doGet()
{
try {
OutputStream outputStream = clientSocket.getOutputStream();
outputStream.write(("HTTP/1.1 200 OK\n\nWorkerThread: " +
"this is by get").getBytes());
outputStream.flush();
outputStream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
@Override
public void run() {
try {
InputStream input = clientSocket.getInputStream();
byte[] byteBuffer = new byte[1000];
input.read(byteBuffer);
for (byte a :byteBuffer)
System.out.print((char)a);
if(byteBuffer[0] == 'G' && byteBuffer[1] == 'E' && byteBuffer[2] == 'T')
{
doGet();
}
else {
doPost();
}
input.close();
System.out.println("接收到請求");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
4主守、基于JDK實現(xiàn)簡單的Web服務(wù)器
其實JDK中已經(jīng)有了對HTTPServer的支持禀倔,我們來簡單應(yīng)用下
public class APITest {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/test", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
String response = "This is the APITest";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}