Linux 环境 HTTP 服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <sys/socket.h>
 
#define BUF_LEN 1028 // 1028 ever
#define PORT 8000
const static char html_re_hd_su[] = "HTTP/1.1 200 OK\r\nContent-type: text/html\r\n\r\n"; //html response header : success
 
int CreatTcpSocket_fd(){
    int socket_fd;
    struct sockaddr_in address;
    socket_fd = socket(AF_INET, SOCK_STREAM, 0); //tcp protocal
    //catch up exception
    if(socket_fd < 0){
        printf("socket creation failed\n");
        exit(1); // 1 means exit with exception
        return 1;
    }
 
    //step 2: bind the socket file description
    memset(&address, 0, sizeof(address));
    address.sin_family = AF_INET; //Internet protocal
    address.sin_port = htons(PORT);
    address.sin_addr.s_addr = INADDR_ANY; //set the host ip
    if(bind(socket_fd, (struct sockaddr*)&address, sizeof(struct sockaddr_in))){
        //catch up exception
        printf("socket binding failed!\n");
        exit(1);
        return 1;
    }
    return socket_fd;
}
 
void AnalyseTcpRequest(const int socket_fd){
    char requestMessage[BUF_LEN];
    read(socket_fd, requestMessage, BUF_LEN);
    printf("%s\n", requestMessage);
}
 
void ReplyTcpRequest(int socket_fd){
    char replyMessage[]=
        "<html><head><title>Welcome!</title></head>" 
        "<body><h1>Welcome to Feng YuBo HTTP server demo!</h1>" 
        "<p>This is a just small test page.</p></body></html>"
 
    write(socket_fd, html_re_hd_su, strlen(html_re_hd_su));
    write(socket_fd, replyMessage, strlen(replyMessage));
    printf("replyed...\n");
}
 
int main(){
    int socket_fd = CreatTcpSocket_fd();
    listen(socket_fd, 5); //max conection number is 5 now.
     
    //step 3: begin to accept tcp request
    struct sockaddr_in their_address;
    int their_sin_len = sizeof(struct sockaddr_in);
     
    for ( ; ; )
    {  
        printf("begin to accept tcp request...\n");
        //begin to block the processing
        int newSocket_fd = accept(socket_fd, (struct sockaddr*)&their_address, &their_sin_len);
        printf("analysing...\n");
        AnalyseTcpRequest(newSocket_fd);
        ReplyTcpRequest(newSocket_fd);
        close(newSocket_fd);
    }
 
    exit(0);
    return 0;
}

 目标: 1.接收HTTP请求  2.打印HTTP请求报文  3.返回HTTP响应报文  4.返回预设好的网页

posted @   健康平安快乐  阅读(287)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示