日期:2014-05-16 浏览次数:20840 次
//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服务器端只会收到1234 using 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; }