我正在爲我的課程使用C++的簡單服務器程序。我們的教授給我們提供了框架代碼,以及評論中的指示。我完成了它,並且它在Unix中編譯,但是我遇到了來自客戶端的密碼認證問題。它是這樣寫的,它可以打印所有可能的選項,但仍不會打印結果。這是程序的功能。 (如果需要,我可以提供整個功能)。所以我的問題是,我的邏輯是否有缺陷,或者是一些小錯誤?TCP服務器C++程序
// PURPOSE: To send 'GOOD_PASSWORD_RESPONSE' to the client over socket file
// descriptor 'clientFD' and return 'true' if the password 'read()' from
// 'clientFD' matches 'password', or to send 'BAD_PASSWORD_RESPONSE' to
// the client and return 'false' otherwise.
bool didLogin(int clientFD, const char *password) {
// I. Application validity check:
printf("Process %d authenticating user . . .\n", getpid());
fflush(stdout);
// II. See if user successfully logged-in:
// II.A. Obtain user's password:
char buffer[MAX_LINE];
size_t size = sizeof(buffer);
read(clientFD, buffer, size);
for (int i = 0; i < sizeof(buffer); i++) {
printf("%c", buffer[i]);
}
// II.B. Handle when user's password does NOT match:
if (strncmp(buffer, password, MAX_PASSWORD_LEN) != 0) {
strncpy(BAD_PASSWORD_RESPONSE, buffer, MAX_LINE);
printf("Process %d bad password.\n", getpid());
return (false);
}
// II.C. If get here then user's password does match:
strncpy(GOOD_PASSWORD_RESPONSE, buffer, MAX_LINE);
printf("Process %d good password.\n", getpid());
// III. Finished:
return (true);
}
什麼樣的優秀例子說明如何不使用C++;如何不認證;沒有正確的初始化/大小參數,怎麼不使用原始緩衝區如何不將業務邏輯與協議實現混合(傳輸細節)。提示:'read'的返回值被忽略。這可能不應該發生 – sehe
@sehe大聲笑,'應該可能不會發生';它幾乎擰了一切:) –
感謝您的幫助,我知道它不是正確的做法,但我必須嚴格遵守提供的骨架代碼。 –