您好,登錄后才能下訂單哦!
UDP協議的主要特點:
UDP是無連接的
UDP使用盡最大努力交付
UDP是面向報文的
沒有擁塞控制
支持一對一、一對多、多對一、多對多的交互通信
UDP首部開銷小
UDP協議是無連接的并且面向數據塊的。所以client端不需要與server端進行連接,直接發送消息。
server: 1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<sys/types.h> 4 #include<sys/socket.h> 5 #include<netinet/in.h> 6 #include<arpa/inet.h> 7 #include<string.h> 8 void usage(char *port) 9 { 10 printf("%s,[ip],[port]\n",port); 11 } 12 int main(int argc,char *argv[]) 13 { 14 if(argc!=3) 15 { 16 usage(argv[0]); 17 exit(1); 18 } 19 int sock = socket(AF_INET,SOCK_DGRAM,0); //創建套接字 20 if(sock<0) 21 { 22 perror("socket"); 23 return 1; 24 } 25 int port = atoi(argv[2]); 26 char *ip = argv[1]; 27 struct sockaddr_in client; 28 client.sin_family = AF_INET; 29 client.sin_port = htons(port); 30 client.sin_addr.s_addr = inet_addr(ip); 31 if(bind(sock,(struct sockaddr*)&client,sizeof(client))<0) 32 { 33 perror("bind"); 34 exit(1); 35 } 36 char buf[1024]; 37 struct sockaddr_in remote; 38 socklen_t len = sizeof(remote); 39 while(1) 40 { 41 ssize_t size = recvfrom(sock,buf,sizeof(buf),0,(struct sockaddr*)&re mote,&len); //接收消息 42 if(size>0) 43 { 44 buf[size-1]='\0'; 45 printf("%s,%d: %s\n",inet_ntoa(remote.sin_addr),ntohs(remote.sin _port),buf); 46 47 } 48 else if(size==0) 49 {} 50 else 51 { 52 perror("recvfrom"); 53 exit(2); 54 } 55 fflush(stdout); 56 } 57 return 0; 58 } client: 1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<sys/types.h> 4 #include<sys/socket.h> 5 #include<string.h> 6 #include<unistd.h> 7 #include<netinet/in.h> 8 #include<arpa/inet.h> 9 void usage(char *port) 10 { 11 printf("%s,[ip],[port]\n",port); 12 } 13 int main(int argc,char *argv[]) 14 { 15 if(argc!=3) 16 { 17 usage(argv[0]); 18 exit(1); 19 } 20 int sock = socket(AF_INET,SOCK_DGRAM,0); 21 if(sock<0) 22 { 23 perror("socket"); 24 return 1; 25 } 26 int port = atoi(argv[2]); 27 char *ip = argv[1]; 28 struct sockaddr_in remote; 29 remote.sin_family = AF_INET; 30 remote.sin_port = htons(port); 31 remote.sin_addr.s_addr = inet_addr(ip); 32 char buf[1024]; 33 while(1) 34 { 35 memset(buf,'\0',sizeof(buf)); 36 ssize_t _s = read(0,buf,sizeof(buf)-1); 37 if(_s<0) 38 { 39 perror("read"); 40 exit(1); 41 } 42 ssize_t size = sendto(sock,buf,strlen(buf),0,(struct sockaddr*)&remo te,sizeof(remote)); //發送消息 43 if(size<0) 44 { 45 perror("sendto"); 46 exit(1); 47 } 48 49 } 50 return 0; 51 } [fbl@localhost udp]$ ./server 192.168.1.106 8080 192.168.1.106,33647: how are you 192.168.1.106,33647: hi 192.168.1.106,33647: hnxu ^C [fbl@localhost udp]$ [fbl@localhost udp]$ ./client 192.168.1.106 8080 how are you hi hnxu ^C [fbl@localhost udp]$
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。