這個項目底層是用Boost.Asio庫,通過正則表達式reg解析http,然後做出響應。
具體做法文末鏈接有詳細介紹,在這裏說一下這個項目得到的知識點,首先是reg正則表達式的用法
regex/regex_match/smatch
regex是用來定義正則表達式的,smatch是用來局部匹配的,regex_match是用來尋找的。具體用法如下:
string fnames[]= {"foo.txt", "bar.txt", "test", "a0.txt", "AAA.txt"};
regex base_regex("([a-z]+)\\.txt");
smatch base_match;
for(auto &fname:fnames){
if(regex_match(fname,base_match,base_regex)){
for(int i=1;i<base_match.size();i++)
cout<<"sub-match "<<base_match[i]<<endl;
}
}
常用IO庫
- iostream
- fstream
- stringstream
getline
典型用法
string s;
while(getline(cin,s)){
do();
}
- 輸入回車,getline也不會跳出while,因爲getline返回的是第一個參數,而不是第二個參數,所以只能用ctlr+z來退出
- getline可以通過第三個參數來規定結束符,沒有第三個參數,默認是”\n”,所以可以如下用法
getline(cin,s,"#")
,遇到‘#’即退出,但是要注意,如果輸入hello#world,再輸入!#,則第一次會得到hello,第二次會得到world!
rdbuf
典型用法
- 文件複製
fstream f1("1"); ftream f2("2");f1>>f2.rdbuf
- stream類轉string類
stringstream ss;ostream os();os>>ss.rdbuf();
-
Boost.Asio 的buffer與streambuf
read可以用buffer,streambuf.
read_until只能用streambuf,
用streambuf好處是
- 不用自己開闢空間
- 可以很方便地與c++中的stream類共同處理
streambuf典型用法如下
streambuf write_buf;
ostream stream(write_buf.get());
op_ostream();
asyn_write(*socket,*write_buf)
streambuf read_buf;
asyn_read(*socket,read_buf...);
istream stream(read_buffer.get());
op_stream();//在這裏通過stream解析剛剛收到的東西
其他小知識點
- 用到模板類,必須同時包含.hpp和.cpp,因爲c++不能支持分離編譯
- openssl被分爲兩部分,apt-get install openssl是應用程序,而apt-get install libssl-dev是用於開發的庫。安裝完libssl-dev後,可以同pkg-config –libs openssl 來查看用openssl時,必須鏈接的庫
項目講解
本項目中,由於要同時支持http,https,所以先寫了個基類BaseServer,然後HttpServer,HttpsServer,分別繼承,因爲,兩種差別在於用到的socket,還用accept方式,http用的是ip::tcp::socket所以,https用的是ssl::stream,所以BaseServer是用模板,到時候再將不同的socket傳入即可,因爲只有accept不同,其他都一樣,所以只需子類複寫accept函數即可,又因爲基類BaseServer的start函數中會調用accept()函數,爲了能夠讓子類調用到他們自己的函數,所以,accept()必須爲virtual。
參考鏈接
http://blog.csdn.net/watson2016/article/details/52415382