99-Linux_C语言实现web服务器

一.单线程实现web服务器

1.代码:

ser.c

#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<sys/socket.h>
#include<stdlib.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<fcntl.h>

int socket_init();
int  recv_request(int c);//接收请求
void send_response(int c);//应答恢复
int main()
{
   
    int sockfd=socket_init();
    if(sockfd==-1)
    {
   
        printf("socket error\n");
        exit(0);
    }

    while(1)
    {
   
        struct sockaddr_in caddr;
        int len=sizeof(caddr);
        int  c=accept(sockfd,(struct sockaddr*)&caddr,&len);//阻塞---浏览器连接,返回
        if(c<0)
        {
   
            continue;
        }

        recv_request(c);//接收请求
        send_response(c);//应答恢复
        close(c);
    }
    exit(0);
}

int  recv_request(int c)//接收请求
{
   
    char buff[1024]={
   0};
    int n=recv(c,buff,1023,0);
    if(n<0)
    {
   
        return -1;
    }
    printf("recv:%s",buff);
}



void send_response(int c)//应答恢复
{
   
    char http_buff[1024]={
   "HTTP 1.1 200 ok\r\n"};
    strcat(http_buff,"Server:http\r\n");

    int fd=open("index.html",O_RDONLY);
    if(fd==-1)
    {
   
        printf("open file error\n");
        return;
    }

    int filesize=lseek(fd,0,SEEK_END);
    
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值