Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Linux网络编程select模型的实现

简单的使用linux下的select模型实现了一个http的server#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 "
"Date: Sat, 05 Jan 2013 03:13:29 GMT "
"Vary: Accept-Encoding "
"Content-Type: text/html; charset=gb2312 "
"Accept-Ranges: bytes "
"Content-Length: 57 "
" "
"<html> <head>欢迎光临</head> <body>屌丝逆袭季</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("异常退出 ");
}
else
{
printf("网络异常");
exit(-1);
}
}
else if(n == 0)
{
close(clientFd);
FD_CLR(clientFd, &fds);
printf("正常退出 ");
}
else
{
line[n] = 0;
printf("接收到数据:%s ", 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("10.132.10.64", &(servaddr.sin_addr));
//servaddr.sin_addr.s_addr = inet_addr("10.132.10.64");
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函数执行成功 ");//select 部分int maxfd;
FD_ZERO(&fds);do{
FD_SET(listenFd, &fds);
maxfd = listenFd + 1;
int nRead = 0;
if( (nRead = select(maxfd + 1, &fds, NULL, NULL, NULL)) < 0)
{
printf("select 失败 ");
exit(-1);
}
printf("select find data Change ");
for(int i = 0; i <= maxfd && nRead > 0; 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 ");
         continue;
}
}
printf("Ip: %s 到此一游 ", inet_ntoa(cliaddr.sin_addr));
FD_SET(connfd, &fds);
maxfd = (connfd > maxfd ? connfd : maxfd);
}
else
{
echo_srv(i);
}
}}while(true);return 0;
}直接用浏览器进行测试即可:http://服务器Ip地址:10088