我試圖"-1"使用send()函式從服務器向客戶端發送一個指標,但是recv()客戶端的函式只接收 1 個位元組的資料(回傳recv()值為 1)。
代碼
服務器端:
get_fd(buf, fd, stat_buf)根據輸入的數字獲取檔案描述符,如果一切正常,輸入的數字無效則buf回傳。-1buf0
if(get_fd(buf, fd, stat_buf) == -1){ // invalid file number
printf("client has given an invalid file number\n\n");
if(send(new_sockfd, "-1", 3, 0) == -1){
perror("client: send");
}
close(new_sockfd);
exit(1);
} else { // valid file number
/* code */
}
當我在客戶端輸入一個無效的檔案號時,printf()第二行的作業正常并且沒有perror()看到任何訊息。
客戶端:
std::memset(&buf, 0, MAXDATASIZE); // clear the buffer for it has been used previously
if((numbyte = recv(sockfd, buf, MAXDATASIZE-1, 0))==-1){
perror("client: recv");
exit(1);
}
buf[numbyte] = '\0';
printf("numbyte: %d, received: %s\n\n", numbyte, buf);
Thenumbyte始終為 1,而as 不printf()列印任何內容,但是當將 the 列印為( ) 時,它會列印一個無意義的負數,例如。bufstringbufint%d-333179216
uj5u.com熱心網友回復:
問題出在連接開始時服務器向send()客戶端發送 ( ) 的第一條訊息。您將 設定len為一個比其實際長度大得多的數字。它在開始時作業正常,因為沒有更多的通信,但是當您再次嘗試send()通過該套接字時會出現問題。
代碼(完整性很重要):
if(send(new_sockfd, "some words here...", 65535, 0) == -1){
perror("server: send");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/359017.html
標籤:C 苹果系统 插座 network-programming
