select写的UDP/TCP测试服务器

发布时间:2016-12-9 9:51:51 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"select写的UDP/TCP测试服务器",主要涉及到select写的UDP/TCP测试服务器方面的内容,对于select写的UDP/TCP测试服务器感兴趣的同学可以参考一下。

比较简单,只是把接收的数据长度打印一下。 #include <unistd.h> #include <arpa/inet.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> #include <netdb.h> #include <malloc.h> #include <netinet/in.h> #include <errno.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #define MODE(a) (a==0?"tcp":"udp") #define BUF_SIZE 2048 void usage(const char *name) { printf("usage: %s [mode<0-tcp,1-udp>] [port<1-65535>]\n",name); printf("example: %s 0 5678, mean listen on port 5678 using tcp mode\n",name); } const char* nowtime() { time_t now = time(NULL); //struct tm *clock = localtime(&now); return ctime(&now); } int sock_setup(int mode, unsigned short port) { int sock = -1; if(mode==0) { sock = socket(AF_INET,SOCK_STREAM,0); } else { sock = socket(AF_INET,SOCK_DGRAM,0); } if(sock<0) return sock; sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = htons(port); sin.sin_addr.s_addr = INADDR_ANY; if(bind(sock,(struct sockaddr*)&sin,sizeof(sin))<0) { printf("bind to %hu failed: %s\n",port,strerror(errno)); close(sock); return -1; } if(mode==0 && listen(sock,5)<0) { close(sock); return -1; } return sock; } int main(int argc, const char **argv) { if(argc<3) { usage(argv[0]); return -1; } int mode = atoi(argv[1]); unsigned short port = atoi(argv[2]); int sock = -1; printf("prepare to bind to %hu & running at %s mode\n",port,MODE(mode)); if((sock=sock_setup(mode,port))>=0) { printf("bind to %hu success\n",port); } else { return -1; } struct timeval tv; int ret; int max_sock_num = sock; fd_set allfd; char buf[BUF_SIZE] = {0}; FD_SET(sock,&allfd); while(true) { fd_set readfd = allfd; tv.tv_sec = 1; tv.tv_usec = 0; ret = select(max_sock_num+1, &readfd, NULL, NULL, &tv); if (ret<0) { printf("select() error: %s\n", strerror(errno)); continue; } else if (ret == 0) { continue; } else { if(FD_ISSET(sock,&readfd)) { sockaddr_in caddr; socklen_t clen = sizeof(caddr); if(mode==0)// tcp { int client = accept(sock,(struct sockaddr*)&caddr,&clen); if(client<0) continue; FD_SET(client,&allfd); if(client>max_sock_num) max_sock_num=client; continue; } else// udp { ret = recvfrom(sock,buf,BUF_SIZE,0,(struct sockaddr*)&caddr,&clen); buf[ret] = 0; printf("%d recvrom %s:%hu %d bytes\n",sock, inet_ntoa(caddr.sin_addr),ntohs(caddr.sin_port),ret); sendto(sock,buf,ret,0,(struct sockaddr*)&caddr,sizeof(caddr));// flood } } for(int i=0;i<max_sock_num+1;i++) { if(i!=sock && FD_ISSET(i,&readfd)) { ret = recv(i,buf,BUF_SIZE,0); if(ret<=0) { FD_CLR(i,&allfd); printf("socket %d was colsed, ret=%d\n",i,ret); close(i); } else { buf[ret] = 0; printf("%d recv %d bytes\n",i,ret); } } } } } return 0; }

上一篇:Linux 2.6.19.x 内核编译配置选项简介
下一篇:MINA2.0用户手册中文版--第三章 第三节 服务端接口IoAcceptor

相关文章

相关评论