网络编程---UDP
1.UDP:用户数据报协议,位于传输层
2.特性:
a.无连接---发送完数据后,发送的链路自动释放,所以每次发送数据前都需要简历链路连接
b.不可靠---在发送过程中,数据在任何一个节点上都可能会丢失
c.大数据---同等情况下,UDP协议比TCP协议一包数据的正文更多
3.UDP框架:C/S模式
注意:服务端一定要先收后发
4.示例:向客户端发送一张图片
ser端
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */#include <arpa/inet.h>
typedef struct sockaddr*(SA);
int main(int argc, char **argv)
{if(argc!=2){printf("Usage:%s<filename>\n",argv[0]);return 1;}FILE*fd=fopen(argv[1], "r");if(fd==NULL){perror("fopen fail");return 1;}int sockfd=socket(AF_INET, SOCK_DGRAM, 0);if(-1==sockfd){perror("sockt fail\n");return 1;}
//man 7 ipstruct sockaddr_in ser,cli;ser.sin_family=AF_INET;//host to net shortser.sin_port=htons(50000);ser.sin_addr.s_addr=inet_addr("192.168.1.53");int ret=bind(sockfd,(SA)&ser,sizeof(ser));if(-1==ret){perror("bind fail\n");return 1;}socklen_t len=sizeof(cli);char buf[1024]={0};int n;while (1){ char temp[512]={0};recvfrom(sockfd, temp, sizeof(temp),0,(SA) &cli, &len);bzero(buf, sizeof(buf));n=fread(buf, sizeof(char), sizeof(buf), fd);if(n<=0){break;}sendto(sockfd, buf, n, 0, (SA)&cli, len); }char temp[512]="finish";sendto(sockfd, temp, sizeof(temp), 0, (SA)&cli, len);close(sockfd);fclose(fd);return 0;
}
cli端
#include <stdlib.h>
#include <strings.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <arpa/inet.h>
typedef struct sockaddr*(SA);
int main(int argc, char **argv)
{FILE*fd=fopen("picture_2.png", "w");if(fd==NULL){perror("fopen fail");return 1;}int sockfd=socket(AF_INET, SOCK_DGRAM, 0);if(-1==sockfd){perror("socket fail\n");return 1;}struct sockaddr_in ser,cli;ser.sin_family=AF_INET;//host to net shortser.sin_port=htons(50000);ser.sin_addr.s_addr=inet_addr("192.168.1.53");while(1){char buf[1024]={0}; char temp[512]="hello";sendto(sockfd, temp,sizeof(temp), 0, (SA)&ser, sizeof(ser));ssize_t n=recvfrom(sockfd, buf, sizeof(buf), 0, NULL, NULL);if(n < 0) {perror("recvfrom error");break;}if(0==strcmp(buf, "finish")){break;}fwrite(buf, sizeof(char), n, fd);}close(sockfd);fclose(fd);return 0;}