UDP是一种无连接的尽最大努力交付的不可靠连接,通信之前无需先建立连接,自然而然,通信之后也就无需再释放连接。
下面是UDP的应用举例
服务端
#include
#include
#include
#include
#include
#include
#include
#include
int main()
{
int sockfd = socket(AF_INET,SOCK_DGRAM,0);
assert( sockfd != -1 );
struct sockaddr_in saddr,caddr;
memset(&saddr,0,sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_port = htons(6000);
saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
int res = bind(sockfd,(struct sockaddr*)&saddr,sizeof(saddr));
assert( res != -1 );
while( 1 )
{
int len = sizeof(caddr);
char buff[128] = {0};
recvfrom(sockfd,buff,127,0,(struct sockaddr*)&caddr,&len);
printf("recv: ip:%s,port:%d,buff=%s\n",inet_ntoa(caddr.sin_addr), ntohs(caddr.sin_port),buff );
sendto(sockfd,"ok",2,0,(struct sockaddr*)&caddr,sizeof(caddr));
sleep(1);
}
close(sockfd);
}
运行结果
recv: ip:127.0.0.1,port:41821,buff=send!!!!
recv: ip:127.0.0.1,port:41821,buff=send!!!!
recv: ip:127.0.0.1,port:41821,buff=send!!!!
recv: ip:127.0.0.1,port:41821,buff=send!!!!
recv: ip:127.0.0.1,port:41821,buff=send!!!!
recv: ip:127.0.0.1,port:41821,buff=send!!!!
客户端
#include
#include
#include
#include
#include
#include
#include
#include
int main()
{
int sockfd = socket(AF_INET,SOCK_DGRAM,0);
assert( sockfd != -1 );
struct sockaddr_in saddr;
memset(&saddr,0,sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_port = htons(6000);
saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
while( 1 )
{
char buff[128] = "send!!!!\n";
sendto(sockfd,buff,strlen(buff),0,(struct sockaddr*)&saddr,sizeof(saddr));
memset(buff,0,128);
int len = sizeof(saddr);
recvfrom(sockfd,buff,127,0,(struct sockaddr*)&saddr,&len);
printf("recv=%s\n",buff);
sleep(1);
}
close(sockfd);
}
运行结果
recv=ok
recv=ok
recv=ok
recv=ok
recv=ok
recv=ok