我有一个通过套接字进行通信的客户端和服务器。我像这样设置它们:
sockfd = socket(AF_INET, SOCK_STREAM, 0);
...
Run Code Online (Sandbox Code Playgroud)
客户端联系服务器,服务器发送响应(在我的测试用例中为2906字节):
n = write(newsockfd, msgout,strlen(msgout));
if (n < 0){
printf("Unable to send reponse.\n");
}else{
printf("Response sent.\n");
}
Run Code Online (Sandbox Code Playgroud)
客户端读取如下响应:
n = read(sockfd,buffer,sizeof(buffer));
if (n < 0){
printf("Socket error.\n");
}else{
printf("%d bytes read.\n", n);
}
Run Code Online (Sandbox Code Playgroud)
缓冲区的大小约为10000个字节。现在经常发生这种情况(占所有情况的25%-75%的时间),只有1448字节到达客户端。没有比这更多的数字或1448。您如何处理这种数据丢失情况,为什么会发生?TCP / IP不能确保没有数据丢失吗?由于错误率很高,因此套接字连接对我几乎没有用。即使我先将邮件的大小发送给客户端。谁保证此消息会到达?如果确实如此,那么我仍然需要一遍又一遍地重新发送主要消息。
我只是用更大的字符串(14538)字节再次尝试了一下,在所有情况下100%仅到达5792字节。所以我猜我的代码中有一个编程错误。但是我看不到。
这是我的测试案例(Linux):
客户:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <time.h>
int main(int argc, char *argv[]){
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
int …Run Code Online (Sandbox Code Playgroud)