UDP编程模型
文章目錄
- 1 UDP編程模型
1 UDP編程模型
UDP編程模型如下:
UDP編程示例代碼:
udp_server.c:
//服務(wù)器端代碼 server.c #include <stdio.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <arpa/inet.h>int main(int argc, char **argv) {int ret;struct sockaddr_in servaddr;char recvline[1024];//SOCK_STREAMint sockfd = socket(PF_INET, SOCK_DGRAM, 0);//服務(wù)器 ip portbzero(&servaddr, sizeof(servaddr));servaddr.sin_family = AF_INET;servaddr.sin_addr.s_addr = htonl(INADDR_ANY);servaddr.sin_port = htons(50001);//fcntl(sockfd, F_SETFL,O_NONBLOCK);//設(shè)置為非阻塞,根據(jù)具體需要決定是否需要非阻塞模式bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));while(1){struct sockaddr_in addrClient;int sizeClientAddr = sizeof(struct sockaddr_in);ret = recvfrom(sockfd, recvline, 1024, 0, (struct sockaddr*)&addrClient,(socklen_t*)&sizeClientAddr);char *pClientIP =inet_ntoa(addrClient.sin_addr);printf("%s-%d(%d) says:%s\n",pClientIP,ntohs(addrClient.sin_port),addrClient.sin_port, recvline);sendto(sockfd, recvline, ret, 0, (struct sockaddr *)&addrClient, sizeClientAddr);}close(sockfd); }udp_client.c:
//客戶端代碼 client.c #include <stdio.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <arpa/inet.h>int main(int argc,char **argv) {int ret;char recvline[1024];int sockfd = socket(PF_INET, SOCK_DGRAM, 0);//server ip portstruct sockaddr_in servaddr;struct sockaddr_in client_addr;char sendline[100] = "hello world!";bzero(&servaddr,sizeof(servaddr));servaddr.sin_family = AF_INET;servaddr.sin_port = htons(50001);servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");//my ip port (bind),也可以不綁定本地port,那么本地發(fā)送的port就是隨機(jī)的。bzero(&client_addr,sizeof(client_addr));client_addr.sin_family = AF_INET;client_addr.sin_port = htons(40001);client_addr.sin_addr.s_addr = htonl(INADDR_ANY);//client發(fā)出的udp包就是從這個(gè)port發(fā)出if(bind(sockfd, (struct sockaddr *)&client_addr,sizeof(client_addr))<0){printf("video rtcp bind ret < 0\n");}sendto(sockfd, sendline, strlen(sendline) + 1, 0, (struct sockaddr *)&servaddr,sizeof(servaddr));while(1){struct sockaddr_in addrClient;int sizeClientAddr = sizeof(struct sockaddr_in);ret = recvfrom(sockfd, recvline, 1024, 0, (struct sockaddr*)&addrClient,(socklen_t*)&sizeClientAddr);char *pClientIP =inet_ntoa(addrClient.sin_addr);printf("%s-%d(%d) says:%s\n",pClientIP,ntohs(addrClient.sin_port),addrClient.sin_port, recvline);sendto(sockfd, recvline, ret, 0, (struct sockaddr *)&addrClient, sizeClientAddr);}close(sockfd);return 1; }參考資料:
總結(jié)
- 上一篇: 开个小型便利店需要投资多少 店小但是本钱
- 下一篇: 多线程简介