[英]socket c client doesn't receive string
這是客戶端代碼的片段:
connect(DescrittoreClient, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
strcpy(Buffer, filename);
send(DescrittoreClient, Buffer, strlen(Buffer), 0);
fd = open(filename, O_CREAT | O_WRONLY,0644);
while ((nread = read(DescrittoreClient, Buffer, sizeof(Buffer))) != 0) {
write(fd, Buffer, nread);
memset(Buffer,0,sizeof(Buffer));
}
int gg;
while( (gg = recv(DescrittoreClient, Buffer, sizeof(Buffer), 0)) == -1) continue;
printf("%d\n", gg);
printf("Risposta del server: %s\n", Buffer);
close(DescrittoreClient);
return EXIT_SUCCESS;
這是服務器代碼的片段:
while(1){
rc = recv(DescrittoreClient, filename, sizeof(filename), 0);
fd = open(filename, O_RDONLY);
fstat(fd, &stat_buf);
offset = 0;
rc = sendfile(DescrittoreClient, fd, &offset, stat_buf.st_size);
if (rc != stat_buf.st_size) {
fprintf(stderr, "incomplete transfer from sendfile: %d of %d bytes\n", rc, (int)stat_buf.st_size);
exit(1);
}
strcpy(Buffer, "Dati inviati correttamente");
if( (send(DescrittoreClient, Buffer, strlen(Buffer), 0)) == -1){
printf("Errore nell'invio della stringa\n");
close(DescrittoreClient);
close(fd);
exit(1);
}
}
close(DescrittoreServer);
return EXIT_SUCCESS;
這是預期的行為:
Client --Give me file X--> Server
Server --send the file X--> Client
Server -->send string "File has been sent"--> Client
但這是真實的行為:
Client --Give me file X--> Server
Server --send the file X--> Client
Server -->_NOTHING_--> Client
所以問題是客戶端沒有收到“文件已被發送”。 我已檢查問題是否是服務器端但不是(事實上服務器發送字符串)
(基於上面的評論) - 要實現的是TCP通信是100%基於流的,沒有內置的框架。 這意味着所有TCP層都確保接收方以發送方發送的相同順序接收字節 - 但不保證字節將以與發送時相同的間隔接收。 (例如,如果發送()10個字節,然后20個字節,然后50個字節,接收器可能一次接收所有80個字節,或者63個字節接着17個字節,或者匯總到的任何其他recv()的組合總共80個字節)。
因此,為了以接收器可以正確解釋它們的方式發送多個單獨的項目,您需要定義自己的規則來構建數據。 在您的情況下,您需要發送n個字節的文件數據,后跟一個字符串,接收程序需要知道的是文件數據的字節數。 這樣,一旦它收到(那么多)字節,它就知道剩下的字節是字符串數據,而不只是將它們寫入文件。
我的建議是首先發送文件的大小(如果需要支持大於4千兆字節的文件大小,則為4字節整數或8字節長)。 然后接收代碼將是這樣的:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.