我正在下載200個字符塊中的在線.dat文件,並且一些數據丟失。大多數,但不是所有的塊完全下載,但有些只是部分下載,當我將接收到的數據直接打印到本地文本文件時,缺少字符。使用C中的套接字在TCP傳輸中丟失數據
謝謝。
我正在使用的程序如下。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <netdb.h>
#include <string.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <malloc.h>
#define NOT_EOF 1
#define REACHED_EOF 0
#define BUFFER_SIZE 200
struct sockaddr_storage their_addr;
socklen_t addr_size;
char inputData[200];
int newsocket;
struct timeval timeout;
char sendStr[100];
char method[] = "GET";
char *buffer= (char *)malloc(2*BUFFER_SIZE*sizeof(char));
FILE *testdata=fopen("testRecv.txt","w");
struct addrinfo hints, *result;
memset (&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if(getaddrinfo("www.blahblah.com","80"
, &hints, &result)!=0)
{
freeaddrinfo(result);
puts("Unable to resolve hostname.");
exit(1);
}
newsocket = socket(result->ai_family, result->ai_socktype, 0);
if(newsocket == FAILURE)
{
puts("Unable to create socket.");
freeaddrinfo(result);
close(newsocket);
exit(1);
}
memset(&timeout, 0, sizeof(timeout));
timeout.tv_sec= 10;
timeout.tv_usec= 0;
setsockopt(newsocket, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
setsockopt(newsocket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
if(connect(newsocket, result->ai_addr, result->ai_addrlen) == -1)
{
puts("Could not connect.");
freeaddrinfo(result);
close(newsocket);
exit(1);
}
strcpy(sendStr,method);
strcat(sendStr," /");
strcat(sendStr,subdomain);
strcat(sendStr," HTTP/1.0\r\nHost: ");
strcat(sendStr,hostname);
strcat(sendStr,"\r\n\r\n");
if(send(newsocket,sendStr,strlen(sendStr),0) == FAILURE)
printf("Unable to send message\n");
while(not_eof=NOT_EOF)
{
bytes_recieved=recv(newsocket,buffer,BUFFER_SIZE,0);
fprintf(testdata,"%s",buffer);
if(bytes_recieved == 0 || *(buffer+bytes_recieved) == EOF)
not_eof=REACHED_EOF;
}
向我們展示'recv()'的實際代碼。當然,你不是隻調用一次? – NPE
這是所有的代碼?我看不到文件寫入。 – hmjd
'while(not_eof = NOT_EOF)'這是不對的。在C中,'='是賦值操作符。 –