【发布时间】:2015-09-16 18:22:40
【问题描述】:
我一直在研究如何在 C 中使用 UDP 传输图像,我创建了一个有时有效,有时无效的代码。我认为问题在于有时服务器接收的包多于写入的包。我知道我正在尝试创建 TCP,但这正是我想要的,但不知道该怎么做。
我认为要修复它,客户端应该发送 img 的 buff,并且仅在服务器回复客户端时发送第二部分。
代码如下:
客户:
while (!feof(p))
{
fread(*&c, 1, BLEN, p);
sprintf(buf, "%s", *&c);
temp=sendto(s,buf,BLEN, 0, (struct sockaddr *) &si_other, slen);
//sleep(3);
//printf("%d ",temp);
if(temp < 0)
{
fprintf(stderr,"sendto error.\n");
printf("erro");
exit(1);
}
i++;
}
服务器:
while(1){
if(recvfrom(s, buf, BLEN, 0, (struct sockaddr *) &si_other, (unsigned int *) &slen)==-1){
perror("recvfrom error.\n");
exit(1);
}
//printf("%s ", &si_other);
flagr[0] = buf[0];
flagr[1] = buf[1];
flagr[2] = buf[2];
if (strcmp(flagr, flag) == 0 ){
break;
}
fwrite(buf, 1, BLEN, pp);
i++;
}
【问题讨论】:
-
只是出于好奇,而不是批评……为什么?我的意思是,这应该解决什么,仅使用 TCP 不会?
-
Sendto 设置
errno,因此您应该将fprintf(stderr,"sendto error.\n");替换为perror("sendto")。
标签: c udp file-transfer