全部博文(70)
分类: LINUX
2010-07-01 20:16:02
#include #include #include #include #include #include #include #define BUFFER 800 #define SERV_PORT 3333 int main() { int sockfd,n; socklen_t len; socklen_t src_len; struct sockaddr_in servaddr, cliaddr; char msg[BUFFER]; struct timeval tm; fd_set rd_fd, wr_fd, ex_fd; sockfd = socket(AF_INET, SOCK_DGRAM, 0); /* create a socket */ /* init servaddr */ bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(SERV_PORT); /* bind address and port to socket */ if(bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == -1) { perror("bind error"); exit(1); } src_len = sizeof(cliaddr); FD_ZERO(&rd_fd); FD_SET(sockfd, &rd_fd); tm.tv_sec = 0; tm.tv_usec = 0; while(1) { FD_ZERO(&rd_fd); FD_SET(sockfd, &rd_fd); tm.tv_sec = 1; tm.tv_usec = 0; if(select(sockfd + 1, &rd_fd, NULL, NULL, &tm) <= 0){ continue; } else { printf("%d, %d\n", tm.tv_sec, tm.tv_usec); printf("there is data\n"); if(recvfrom(sockfd, msg, BUFFER, 0, (struct sockaddr *)&cliaddr, &src_len)< 0) { perror("receive error!\n"); exit(0); } printf("%s\n", msg); sleep(5); } } return 0; } |