一个简单的基于多线程的web server

下面是一个朋友chunjian的一个简单的基于多线程的httpd。

/*-------------------------------------------------------------------------------------------------
gcc -o httpd httpd.c -lpthread
author: chunjian,wyezl
2006.4.28
---------------------------------------------------------------------------------------------------*/


#include <sys/sendfile.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

#define PORT 8899
#define MAX_QUEUE 5
#define HELLO "Hello, Httpd!"

void *serv_client(void *p);
main(int argc,char * argv[])
{
    pthread_t tid;
    int opt = 1, fd, cfd;
    struct sockaddr_in sin, cin;
    pthread_attr_t attr;
    socklen_t sin_len = sizeof(struct sockaddr_in);

    if ((fd = socket(AF_INET, SOCK_STREAM, 0)) <= 0)
    {
          fprintf(stderr, "socket failed/n");
          return -1;
    }
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void*)&opt, sizeof(opt));
    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_port = htons((short)(PORT));
    sin.sin_addr.s_addr = INADDR_ANY;
    if (bind(fd, (struct sockaddr *)&sin, sizeof(sin)) != 0)
    {
          fprintf(stderr, "bind failed/n");
          return -1;
    }
    if (listen(fd, MAX_QUEUE) != 0)
    {
          fprintf(stderr, "listen failed/n");
          return -1;
    }
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
    while ((cfd = accept(fd, (struct sockaddr *)&cin, &sin_len)) > 0)
    {
          if (pthread_create(&tid, &attr, serv_client, &cfd) != 0)
                fprintf(stderr, "pthread_create failed/n");
    }

    if (fd > 0)
          close(fd);
    pthread_attr_destroy(&attr);
    return 0;
}

void *serv_client(void *p)
{
    int cfd = *((int *)p);


    printf("cfd=%d/n",cfd);
    char buffer[1024] = {0};
    char hello[1024]="yangjian/n";

    fprintf(stderr, "1 user come into.../n");
    sprintf(buffer, "HTTP/1.1 200 OK/r/nContent-Length: %d/r/nConnection: close/r/nContent-Type: text/html/r/n/r/n%s", strlen(hello), hello);
    send(cfd, buffer, strlen(buffer), 0);
    printf("len=%d/n",strlen(hello));


    shutdown(cfd,1);
    close(cfd);
    return NULL;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值