Báo cáo đồ án Socket, bộ môn Mạng máy tính
STT | Họ và tên | MSSV |
---|---|---|
1 | Nguyễn Gia Thụy | 1712809 |
2 | Lý Quốc Bình | 1712292 |
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
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:
Nhập username
và password
đượ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:
Nếu nhập sai, trình duyệt báo lỗi trên trang index.html như hình:
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:
- 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í)