/* 這個示例是一個使用了Dlib C++ 庫的server組件的HTTP擴展 它建立一個始終以簡單的HTML表單爲響應的服務器。 要查看這個頁面,你應該訪問 http://localhost:5000 */ #include <iostream> #include <sstream> #include <string> #include <dlib/server.h> using namespace dlib; using namespace std; class web_server : public server_http { const std::string on_request ( const incoming_things& incoming, outgoing_things& outgoing ) { ostringstream sout; // 咱們將發回一個包含HTML表單的頁面,其中包含兩個文本輸入字段。一個字段是name(還有一個是pass) // HTML表單使用post方法,也能夠使用get方法(只需將method='post'改成method='get'). sout <<" <html><meta charset=\"utf-8\"><body> " << "<form action='/form_handler' method='post'> " << "用戶名稱: <input name='user' type='text'><br> " << "用戶密碼: <input name='pass' type='text'> <input type='submit'> " << " </form>"; // 回寫這個請求傳入的一些信息,以便它們顯示在生成的網頁上 sout << "<br> path = " << incoming.path << endl; sout << "<br> request_type = " << incoming.request_type << endl; sout << "<br> content_type = " << incoming.content_type << endl; sout << "<br> protocol = " << incoming.protocol << endl; sout << "<br> foreign_ip = " << incoming.foreign_ip << endl; sout << "<br> foreign_port = " << incoming.foreign_port << endl; sout << "<br> local_ip = " << incoming.local_ip << endl; sout << "<br> local_port = " << incoming.local_port << endl; sout << "<br> body = \"" << incoming.body << "\"" << endl; // 若是此請求是用戶提交表單的結果,則回顯提交 if (incoming.path == "/form_handler") { sout << "<h2> 來自 query string 的信息 </h2>" << endl; sout << "<br> user = " << incoming.queries["user"] << endl; sout << "<br> pass = " << incoming.queries["pass"] << endl; // 將這些表單提交做爲Cookie保存 outgoing.cookies["user"] = incoming.queries["user"]; outgoing.cookies["pass"] = incoming.queries["pass"]; } // 將全部Cookie回傳到客戶端瀏覽器 sout << "<h2>客戶web瀏覽器發送給服務器的 Cookies</h2>"; for ( key_value_map::const_iterator ci = incoming.cookies.begin(); ci != incoming.cookies.end(); ++ci ) { sout << "<br/>" << ci->first << " = " << ci->second << endl; } sout << "<br/><br/>"; sout << "<h2>客戶web瀏覽器發送給服務器的 HTTP Headers</h2>"; // 回顯從客戶端web瀏覽器接收的全部HTTP headers for ( key_value_map_ci::const_iterator ci = incoming.headers.begin(); ci != incoming.headers.end(); ++ci ) { sout << "<br/>" << ci->first << ": " << ci->second << endl; } sout << "</body> </html>"; return sout.str(); } }; int main() { try { // 建立一個 web server 實例對象 web_server our_web_server; // 監聽5000端口 our_web_server.set_listening_port(5000); // 告訴服務器開始接受鏈接。 our_web_server.start_async(); cout << "請按Enter(回車)鍵去結束程序" << endl; cin.get(); } catch (exception& e) { // 上面出錯會拋出異常 // 輸出異常消息 cout << e.what() << endl; } }