嵌入式 Linux网络编程(三)――UDP编程模型
UDP编程模型:
UDP循环服务器模型为:
socket(...);
bind(...);
while(1)
{
recvfrom(...);
process(...);
sendto(...);
}
server.c代码:
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h> #define PORT 8888#define BUFFER_SIZE 1024 int main(int argc, char *argv[]){int sockfd;sockfd = socket(AF_INET, SOCK_DGRAM, 0); // 创建udp套接字if(sockfd < 0){fprintf(stderr, "socket function failed.\n");exit(-1);}struct sockaddr_in server_addr;bzero(&server_addr, sizeof(server_addr));server_addr.sin_family = AF_INET;// IPv4server_addr.sin_port = htons(PORT);// 端口server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // ip// 绑定int err;err = bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));if(err != 0){fprintf(stderr, "bind function failed.\n");close(sockfd);exit(-1);}fprintf(stdout, "server runiing on %d\n", PORT);char recvbuf[BUFFER_SIZE];struct sockaddr_in client_addr;while(1){int recvlen;bzero(&recvbuf, sizeof(recvbuf));socklen_t len = sizeof(client_addr);bzero(&client_addr, sizeof(client_addr));if(strcmp(recvbuf,"exit\n")==0) break; if(strcmp(recvbuf,"q\n")==0) break; if(strcmp(recvbuf,"quit\n")==0) break;// 接收客户端数据recvlen = recvfrom(sockfd, recvbuf, sizeof(recvbuf), 0, (struct sockaddr*)&client_addr, &len);fprintf(stdout, "have a new client :%s, port:%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port)); // 客户端的ipprintf("message: %s\n", recvbuf);sendto(sockfd, recvbuf, recvlen, 0, (struct sockaddr*)&client_addr, len);}close(sockfd);return 0;}
client.c代码:
#include <sys/types.h>#include <sys/socket.h>#include <stdio.h>#include <netinet/in.h>#include <arpa/inet.h>#include <unistd.h>#include <string.h>#include <stdlib.h>#include <fcntl.h>#include <sys/shm.h> #define PORT 8888#define BUFFER_SIZE 1024 int main(){ ///定义sockfd int clientsockfd = socket(AF_INET, SOCK_DGRAM, 0); ///定义sockaddr_in struct sockaddr_in servaddr; bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(PORT); ///服务器端口 servaddr.sin_addr.s_addr = inet_addr("192.168.0.200"); ///服务器ip ///连接服务器,成功返回0,错误返回-1 if (connect(clientsockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) { fprintf(stderr, "connect function failed.\n"); exit(-1); } char sendbuf[BUFFER_SIZE]; char recvbuf[BUFFER_SIZE]; bzero(sendbuf, sizeof(sendbuf)); bzero(recvbuf, sizeof(recvbuf)); while (1) { fgets(sendbuf, sizeof(sendbuf), stdin); if(strcmp(sendbuf,"exit\n")==0) break; if(strcmp(sendbuf,"q\n")==0) break; if(strcmp(sendbuf,"quit\n")==0) break; send(clientsockfd, sendbuf, strlen(sendbuf),0); ///发送 recv(clientsockfd, recvbuf, sizeof(recvbuf),0); ///接收 fprintf(stdout, "%s\n", recvbuf);bzero(sendbuf, sizeof(sendbuf)); bzero(recvbuf, sizeof(recvbuf)); } close(clientsockfd); return 0;}
本文出自 “生命不息,奋斗不止” 博客,转载请与作者联系!