首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

linux c兑现的简单web响应程序(会完善成一个简单web服务器)

2013-01-18 
linux c实现的简单web响应程序(会完善成一个简单web服务器)#include stdio.h#include stdlib.h#includ

linux c实现的简单web响应程序(会完善成一个简单web服务器)

#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <string.h>#include <sys/socket.h>#include <netinet/in.h>#include <sys/socket.h>#define LINE_LEN 25
//配置文件存储结构struct httppd{    char Port[10];    char Directory[20];    int listenfd;//服务器socket文件监听句柄};
//客户端请求信息结构体struct clientInfo{    struct sockaddr_in cliaddr;    int clifd;};
//读取配置文件,暂时只是一个服务目录跟端口void readDir  (struct httppd *conf){    int fd;    FILE *file = fopen("/etc/myhttp.conf","r");    if(file == NULL)    {        perror("fopen error.");        exit(1);    }    bzero(conf,sizeof(struct httppd));    fscanf(file,"%s",conf->Port);    fscanf(file,"%s",conf->Directory);    strcpy(conf->Port,strchr(conf->Port,'=')+1);    strcpy(conf->Directory,strchr(conf->Directory,'=')+1);    fclose(file);}void *handlClient(void *connfd);void sendMsg(void *cinfo);
//启动服务器void startServer(struct httppd *conf){    struct sockaddr_in servaddr,cliaddr;    int listenfd,connfd;    //建入socket文件句柄    listenfd = socket(AF_INET,SOCK_STREAM,0);    conf->listenfd = listenfd;    //初始化服务器信息    bzero(&servaddr,sizeof(servaddr));    servaddr.sin_family = AF_INET;    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);    servaddr.sin_port = htons(atoi(conf->Port));       if(bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr)) == -1)     {        perror("bind error");        exit(0);    }    listen(listenfd,20);    printf("Accepting connections.......\n");    socklen_t cliaddr_len;    while(1)    {        cliaddr_len = sizeof(cliaddr);        connfd = accept(listenfd,(struct sockaddr *)&cliaddr,&cliaddr_len);        struct clientInfo cinfo;        cinfo.cliaddr = cliaddr;        cinfo.clifd = connfd;
//使用多线路程服务客户端请求,有待完善        pthread_t client;        pthread_create(&client,NULL,handlClient,&cinfo);        pthread_join(client,NULL);        close(connfd);           }}#define MAXLINE 80
//处理客户端请求void *handlClient(void *info){    struct clientInfo cinfo = *(struct clientInfo *)info;    char buf[MAXLINE],n;    n = read(cinfo.clifd,buf,MAXLINE);    if(n < 0)    {        perror("read error....");        exit(0);    }    printf("Recvfrom information is %s\n",buf);    sendMsg(&cinfo);}
//响应客户端请求void sendMsg(void *info){    struct clientInfo cinfo = *(struct clientInfo *)info;    FILE *file = fopen("/var/www/index.html","r");    char buf[1024];    fread(buf,1024,1,file);    //fgets(buf,1024,file);    //printf("index.html %s\n",buf);    sendto(cinfo.clifd,buf,1024,0,(struct sockaddr *)&(cinfo.cliaddr),sizeof(cinfo.cliaddr));    fclose(file);}
//程序入口int main(int argc,char *argv[]){    struct httppd conf;    readDir(&conf);    startServer(&conf);    close(conf.listenfd);    return 0;}
?只是一个练手程序,做个纪念,有待更多的学习与完善。

热点排行