linux编程|select模型实例精讲

时间 : 15-03-11 栏目 : linux编程 作者 : 老薛 评论 : 0 点击 : 1,896 次

/*

* create by www.bdkyr.com

* date 2015-3-11

*/

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <errno.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <stdlib.h>

#define LISTENQ    5
#define OPEN_MAX   1024
#define SERV_PORT  10088
#define MAX_LINE   1024
#define INFTIM     -1
#define MAXEVENTS  1000

char szHtmlBuf[] = "HTTP/1.1 200 OK\r\n"
"Date: Sat, 05 Jan 2013 03:13:29 GMT\r\n"
"Vary: Accept-Encoding\r\n"
"Content-Type: text/html; charset=gb2312\r\n"
"Accept-Ranges: bytes\r\n"
"Content-Length: 57\r\n"
"\r\n"
"<html> <head>欢迎光临</head> <body>linux技术开源人</body></html>";

fd_set fds;

void echo_srv(int clientFd)
{
//处理用户请求数据
char line[MAX_LINE];
printf( "开始读取数据");
int n = read(clientFd, line, sizeof(line));
if(n < 0)
{
//#define ECONNRESET 104  /* Connection reset by peer */
if(errno == ECONNRESET)
{
close(clientFd);
FD_CLR(clientFd, &fds);
printf("异常退出\n");
}
else
{
printf("网络异常");
exit(-1);
}
}
else if(n == 0)
{
close(clientFd);
FD_CLR(clientFd, &fds);
printf("正常退出\n");
}
else
{
line[n] = 0;
printf("接收到数据:%s\n", line);
write(clientFd, szHtmlBuf, sizeof(szHtmlBuf));
}
}

int main()
{
struct sockaddr_in cliaddr, servaddr;
int listenFd = socket(AF_INET, SOCK_STREAM, 0);
if( listenFd < 0)
{
printf("socket函数执行失败");
return 1;
}

servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
//inet_aton('192.168.15.201', &(servaddr.sin_addr));
//servaddr.sin_addr.s_addr = inet_addr("192.168.15.201");
servaddr.sin_port = htons(SERV_PORT);
if(bind(listenFd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0)
{
printf("bind函数执行失败");
return 1;
}

if(listen(listenFd, LISTENQ) < 0)
{
printf("listen函数执行失败");
return 1;
}
printf("listen函数执行成功\n");

//select 部分

int maxfd;
FD_ZERO(&fds);

do{
FD_SET(listenFd, &fds);
maxfd = listenFd + 1;
int nRead = 0,i;
if( (nRead = select(maxfd + 1, &fds, NULL, NULL, NULL)) < 0)
{
printf("select 失败\n");
exit(-1);
}
printf("select find data Change\n");
for(i = 0; i <= maxfd; i++)
{
if(!FD_ISSET(i, &fds))
{
continue;
}
--nRead;
if(i == listenFd)
{
socklen_t clilen = sizeof(cliaddr);
int connfd = accept(listenFd, (struct sockaddr*)&cliaddr, &clilen);
if(connfd < 0)
{
if ((errno != EAGAIN) && (errno != EWOULDBLOCK))
{
printf( "fail to accept new client \n");
continue;
}
}
printf("Ip: %s 到此一游\n", inet_ntoa(cliaddr.sin_addr));
FD_SET(connfd, &fds);
maxfd = (connfd > maxfd ? connfd : maxfd);
}
else
{
echo_srv(i);
}
}

}while(1);

return 0;
}

本文标签

除非注明,文章均为( 老薛 )原创,转载请保留链接: http://www.bdkyr.com/xtyw003/677.html

随便看看

0