[英]C++ UNIX Help - simple TCP server socket connection
我是一名學生,使用 UNIX 系統調用編寫 C++ 代碼,以執行來自終端的簡單服務器 <-> 客戶端請求。 用戶(我)在終端中的兩個程序(服務器和客戶端)的端口中輸入以建立連接,目標是服務器將客戶端程序輸入的內容發送回客戶端。
IE:
終端 1:./server 9000
終端2:./client localhost 9000 ~
將顯示 Home 中所有目錄和文件的列表。
或終端 2:./client localhost 9000 test.txt
將從 test.txt 文件中讀取內容並將其寫入客戶端的終端。
截至目前,只有文件夾有效。 每當我嘗試使用文件時,它都會打印一個空行。 這是我的過程 function 的代碼:
void processClientRequest(int connSock)
{
int received;
char path[1024], buffer[1024];
// Read from the client
if((received = read(connSock, path, sizeof(path))) < 0)
{ perror("receive"); exit(EXIT_FAILURE); }
// Check if it is a directory or a file
struct stat s;
if(stat(path,&s) == 0 )
{
// It is a directory
if(s.st_mode & S_IFDIR)
{
DIR *dirp = opendir(path);
if (dirp == 0)
{
// Tell client they gave the inappropriate input
// Duplicate socket descriptor into error output
// Then print it to client's end with perror to
// Give more in-depth details of the error to user
close(2);
dup(connSock);
perror(path);
exit(EXIT_SUCCESS);
}
struct dirent *dirEntry;
while((dirEntry = readdir(dirp)) != NULL)
{
// If statement to hides all files/folders that start with a dot
// Which are hidden files/folders
if(dirEntry->d_name[0] != '.')
{
strcpy(buffer, dirEntry->d_name);
strcat(buffer, "\n");
if(write(connSock, buffer, strlen(buffer)) < 0)
{ perror("write"); exit(EXIT_FAILURE); }
}
}
closedir(dirp);
close(connSock);
exit(EXIT_SUCCESS);
}
// It is a file
else if(s.st_mode & S_IFREG)
{
int fd = open(path, O_RDONLY);
if(fd < 0) { perror("open"); exit(EXIT_FAILURE); }
read(fd, buffer, strlen(buffer));
strcat(buffer, "\n");
if(write(connSock, buffer, strlen(buffer)) < 0)
{ perror("write"); exit(EXIT_FAILURE); }
close(fd);
}
// Not a file or directory
else
{
cout << "It is neither a file nor directory!" << endl;
exit(EXIT_FAILURE);
}
}
else
{
// Same explanation as line 95 - 98
close(2);
dup(connSock);
perror("stat");
exit(EXIT_SUCCESS);
}
close(connSock);
exit(EXIT_SUCCESS);
}
作為一個附帶問題,我如何讓它在執行過程之前接受/識別代碼字以及雙引號? 截至目前,我只能使用./client... pathname/"name with spaces" ; 如果我使用./client... "pathname/name with spaces"它會顯示一個stat: no such file or directory錯誤。 例如:
./client localhost 4000 "獲取路徑名/文件名"
你的問題在這里:
else if(s.st_mode & S_IFREG)
{
int fd = open(path, O_RDONLY);
if(fd < 0) { perror("open"); exit(EXIT_FAILURE); }
read(fd, buffer, strlen(buffer)); << Change strlen(buffer)
strcat(buffer, "\n");
if(write(connSock, buffer, strlen(buffer)) < 0)
{ perror("write"); exit(EXIT_FAILURE); }
close(fd);
}
strlen(buffer)
可以是任何值,因為您將緩沖區初始化為 1024 字節。 memory 區域可能被填滿了零。 然后strlen(buffer)
將返回 0,因為第一個字符是 null 字節。 沒有任何內容被寫入緩沖區,因為read
最終會寫入零字節。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.