/Socket_WebServer

HCMUS Introduction to Computer Networking. Socket: WebServer

Primary LanguageC++

BÁO CÁO

Version Contributors Size

Báo cáo đồ án Socket, bộ môn Mạng máy tính

Thành viên

STT Họ và tên MSSV
1 Nguyễn Gia Thụy 1712809
2 Lý Quốc Bình 1712292

Nội dung

Mã nguồn

Hàm main của chương trình:

void main() {
	try {
		Server server("3000");
		server.run();
	}
	catch (std::runtime_error& e) {
		std::cout << "Run-time error: " << e.what();
	}
}

Khai báo của lớp Server:

class Server
{
public:
    Server(const std::string& port = DEFAULT_PORT); //Constructor

    void run(); //Operate server
   
    ~Server(); //Destructor

private:
    /*---------- Socket-based methods ----------*/

    void initializeWinSock();

    void createSocket(addrinfo*& result, SOCKET& listenSocket, const char* port); 

    void bindSocket(addrinfo* result, const SOCKET& listenSocket);

    void listenOnSocket(const SOCKET& listenSocket);
    
    SOCKET acceptConnection();

    void handleRequests(SOCKET& clientSocket, const std::string* pages);

    /*---------- Utility methods ----------*/

    void handleGET(const std::string& request, const std::string* pages, std::string& response, bool authorized);

    void handlePOST(const std::string& request, const std::string* pages, std::string& response, bool& authorized);

    std::string getResponse(std::string& content, int statusCode, const std::string& message);

    bool authentify(const std::string& username, const std::string& password);

    void cleanUp();

private:
    char _port[5];
    std::string _pages[4];
    addrinfo* _result;
    SOCKET _listenSocket;
};

Lớp FileReader - Hỗ trợ đọc files:

class FileReader {
public:
	static void readContent(const char* path, std::string& content) {
		std::ifstream reader(path);
		if (reader.is_open()) {
			std::string buffer((std::istreambuf_iterator<char>(reader)),
				(std::istreambuf_iterator<char>()));
			reader.close();
			content = buffer;
		}
		else {
			std::cerr << "Cannot read file\n";
		}
	}
};

Chi tiết xem trong mã nguồn

Demo chương trình

Sau khi chạy chương trình, ta mở trình duyệt và gõ vào localhost:[port] (port tự chọn trong hàm main), trình duyệt sẽ mở file index.html (đường dẫn: localhost:[port]/index.html) như sau:

index

Nhập usernamepassword được quy định trong file userinfo.dat. Nếu nhập đúng trình duyệt sẽ mở file info.html (đường dẫn: localhost:[port]/info.html) như hình:

info

Nếu nhập sai, trình duyệt báo lỗi trên trang index.html như hình:

index_error

Nếu người dùng gõ vào địa chỉ không tồn tại (ví dụ localhost:[port]/helloabc) thì trình duyệt sẽ mở file error.html (đường dẫn: localhost:[port]/error.html) như hình:

error

Lưu ý

  • Trình duyệt:
    • Không hỗ trợ các trình duyệt có lõi Chromium
    • Chạy ổn định nhất trên trình duyệt Microsoft Edge Legacy
  • Chức năng:
    • Chưa có chức năng cấp quyền cho nhiều người dùng khác nhau (hiện tại chỉ 1 người dùng đã được đăng kí)