實現一個簡單的Web伺服器(C語言)
阿新 • • 發佈:2018-12-20
Web伺服器
github地址 該專案的第二部分是在第一部分的基礎上繼續完善Web伺服器。
第二部分主要是完成兩個功能:記錄日誌和HTTP響應。
記錄日誌
該部分比較簡單,只要簡單地將一些伺服器的資訊新增到指定日誌檔案即可, 也不需要完成很複雜的功能,有了日誌功能也方便除錯。
由於要在啟動伺服器時將日誌檔案傳給main函式,所以我將日誌檔名宣告為 全域性變數,方便在整個專案中往日誌檔案中新增日誌資訊。
日誌檔案的操作放在src/log
資料夾中。
HTTP響應
要處理HTTP請求,那必須能解析HTTP請求。
HTTP解析
完成一個HTTP解析器並不是一件簡單的事,感覺難度已經超過了本次專案,
所以我用開源工具flex
bison
來完成對HTTP請求的詞法分析器和語法分析器,
所以要先學習使用這兩個開源工具。入門。
該部分放在src/parse
資料夾中。
GET、HEAD、POST
我只完成這三個最常用的請求方法,主要是瞭解在各種情況下要對請求響應 正確的格式。
該部分放在src/response
資料夾中。
其它
與專案第一部分不同的還有在src/io
中添加了一些檔案操作的函式。
測試
根據課程提供的測試指令碼,通過了所有的測試。
test_using_select (__main__.project1cp2tester) ... Simple checker to tell if you are using select( ). We will check it manually later.
ok
start_server (__main__.project1cp2tester) ... Try to start server!
./lisod 7471 9722 ./lisod.log ../tmp/lisod.lock ../tmp/www ../tmp/cgi/cgi_script.py ../tmp/grader.key ../tmp/grader.crt
Wait 2 seconds.
Server is running
ok
test_HEAD_headers (__main__.project1cp2tester) ... ----- Testing Headers -----
ok
test_HEAD (__main__.project1cp2tester) ... ----- Testing HEAD -----
ok
test_GET (__main__.project1cp2tester) ... ----- Testing GET -----
ok
test_POST (__main__.project1cp2tester) ... ----- Testing POST -----
ok
test_bad (__main__.project1cp2tester) ... ----- Testing Bad Requests-----
ok
test_big (__main__.project1cp2tester) ... ----- Testing Big file -----
ok
test_kill (__main__.project1cp2tester) ... kill it
ok
----------------------------------------------------------------------
Ran 11 tests in 19.567s
OK
{"scores": {"test_make": 1, "test_HEAD_headers": 1, "test_POST": 1, "server_start": 1, "test_git": 1, "use_select": 1, "test_big": 1, "test_bad": 1, "test_GET": 1, "test_HEAD": 1}}
效果
我們可以實際看看加上靜態html有什麼效果。
先啟動伺服器:
./lisod 7471 9722 ./lisod.log ../tmp/lisod.lock ./src/static_site/ ../tmp/cgi/cgi_script.py ../tmp/grader.key ../tmp/grader.crt
在瀏覽器輸入;
localhost:7471
就可以看到下面的畫面: