我无法通过C中的TCP套接字传输文件。我将8192字节的小块文件从服务器发送到客户端。问题是客户端不完整地接收到最后一个,而根本没有接收到最后一个。
这是代码的两个相关部分。 服务器:
fd = open(filename,O_RDONLY);
if (fd == -1)
{
fprintf(stderr, "Error opening file --> %s", strerror(errno));
exit(EXIT_FAILURE);
}
/* Get file stats */
if (fstat(fd, &file_stat) < 0)
{
fprintf(stderr, "Error fstat --> %s", strerror(errno));
exit(EXIT_FAILURE);
}
fprintf(stdout, "File Size: \n%d bytes\n", file_stat.st_size);
sprintf(file_size, "%d", file_stat.st_size);
/* Sending file size */
len = send(peer_socket, file_size, sizeof(file_size), 0);
if (len < 0)
{
fprintf(stderr, "Error on sending greetings --> %s", strerror(errno));
exit(EXIT_FAILURE);
}
fprintf(stdout, "Server sent %d bytes for the size\n", len);
offset = 0;
remain_data = file_stat.st_size;
/* Sending file data */
while(((sent_bytes = sendfile(peer_socket, fd,&offset, BUFSIZ))>0)&&(remain_data > 0))
{
remain_data -= sent_bytes;
fprintf(stdout, "2. Server sent %d bytes from file's data, offset is now : %d and remaining data = %d\n", sent_bytes, offset, remain_data);
}
和客户端:
ecv(client_socket, buffer, BUFSIZ, 0);
file_size = atoi(buffer);
fprintf(stdout, "\nFile size : %d\n", file_size);
//received_file = fclose(fopen(FILENAME, "w"));
received_file = fopen(FILENAME, "w");
if (received_file == NULL)
{
fprintf(stderr, "Failed to open file --> %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
remain_data = file_size;
while ((remain_data > 0)&&((len = recv(client_socket, buffer, BUFSIZ, 0)) > 0))
{
fwrite(buffer, sizeof(char), len, received_file);
remain_data -= len;
//if (remain_data < BUFSIZ)
// buffsize = remain_data;
//bzero(buffer,BUFSIZ);
//if (len == 0 || len != BUFSIZ)
// break;
fprintf(stdout, "Received %d bytes , %d bytes remaining\n", len, remain_data);
}
//code for accelerator here
fclose(received_file);
从那里开始,双方的应用程序永远卡住。知道什么会引起麻烦吗? 感谢您的回答