首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 操作系统 > UNIXLINUX >

为什么服务器端的recvfrom不阻塞等待客户端的数据就返回了?该怎么解决

2012-03-19 
为什么服务器端的recvfrom不阻塞等待客户端的数据就返回了?C/C++ code//server代码#include cstdlib#inc

为什么服务器端的recvfrom不阻塞等待客户端的数据就返回了?

C/C++ code
//server代码#include <cstdlib>#include <cstring>#include <cstdio>#include <unistd.h>#include <sys/socket.h>#include <sys/types.h>#include <iostream>#include <strings.h>#include <arpa/inet.h>       //测试表明tcp服务器端只会收到1234using namespace std;int main(){  int confd,lisfd;  struct sockaddr_in serv;  bzero(&serv,0);  char buf[12];  bzero(buf,0);    serv.sin_family=AF_INET;  serv.sin_port=htons(8989 );  serv.sin_addr.s_addr=htonl(INADDR_ANY);    lisfd=socket(AF_INET,SOCK_DGRAM,0);  bind(lisfd,(struct sockaddr *)&serv,sizeof(struct sockaddr_in));      for(;;)    {       recvfrom(confd,buf,sizeof(buf),0,NULL,NULL);          cout<<buf<<endl;    }  return 0;}//client.cpp 客户端代码#include <unistd.h>#include <sys/socket.h>#include <sys/types.h>#include <iostream>#include <strings.h>#include <arpa/inet.h>       using namespace std;int main(){  int confd;  struct sockaddr_in serv;  bzero(&serv,0);  char p1[]="1234";  char p2[]="5678";    serv.sin_family=AF_INET;  serv.sin_port=htons(8989);  inet_pton(AF_INET,"127.0.0.1",&serv.sin_addr.s_addr);    confd=socket(AF_INET,SOCK_DGRAM,0);     cout<<"send "<<sendto(confd,p1,sizeof(p1),0,(struct sockaddr *)&serv,sizeof(struct sockaddr_in))<<"bytes data!"<<endl;  cout<<"send "<<sendto(confd,p2,sizeof(p2),0,(struct sockaddr *)&serv,sizeof(struct sockaddr_in))<<"bytes data!"<<endl;  close(confd);  return 0;}


请问这是什么原因?谢谢!

[解决办法]
服务器使用 confd 干什么?
recvfrom 失败了,肯定无限循环了
[解决办法]
建议楼主包括其它的初学者,也包括网络编程之外的,当出现问题的时候,应该先看看返回值,这样比你马上来问要来得快,很多人都没有查看函数返回值的习惯,这对维护来说,简直就是灾难!

热点排行