网络编程——HTTP协议介绍及Socket实现HTTP服务器代码编写

HTTP协议

HTTP协议的简介



http URL 介绍

http发送请求

http接收响应

报头header信息






httpwatch工具的使用:https://blog.csdn.net/weixin_38251305/article/details/104062406

http服务器的实现:
例子1,编写一个简单HTTP服务器程序,即服务器解析一个html文件,将结果返回给客户端:1)AF_INET; 2) SOCK_STREAM; 3) Port: 80
功能:http服务器打开一个html.txt文件,将文件内容发送给客户端;且服务器绑定http服务器的80端口,如果客户端是浏览器则将会将服务器发送过来的html.txt的html代码效果显示在浏览器上;
html.txt的html代码如下:

<html>
<body style="background-color:PowderBlue;">

<h1>Look! Styles and colors</h1>

<p style="font-family:verdana;color:red">
This text is in Verdana and red</p>

<p style="font-family:times;color:green">
This text is in Times and green</p>

<p style="font-size:30px">This text is 30 pixels high</p>

</body>
</html>

服务器文件http_server.c;内容如下:

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

int main()
{
        char html_content[2048]={0};
        int fd,rev;
        int client_len;

        
        struct sockaddr_in server,client;
        int server_fd,client_fd;
        //init
        server.sin_family =AF_INET;
        server.sin_addr.s_addr =htonl(INADDR_ANY);
        server.sin_port =htons(80);//http port
        //socket
        server_fd=socket(AF_INET,SOCK_STREAM,0);
        if(server_fd==-1)
        {
        printf("socket error\n");
        exit(1);
        }
        
        //bind
        if(bind(server_fd,(struct sockaddr*)&server,sizeof(server))==-1)
        {
        printf("bind error\n");
        close(server_fd);
        exit(1);
        }
        
        //listen
        if(listen(server_fd,20)==-1)
        {
        printf("listen error\n");
        close(server_fd);
        exit(1);
        }
        client_len=sizeof(client);
        while(1)
        {
        //accept
        client_fd=accept(server_fd,(struct sockaddr *)&client,&client_len);
        if(client_fd ==-1)
        {
        printf("accept error\n");
        close(server_fd);
        exit(1);
        }
        //operation
        fd=open("./html.txt",O_RDONLY);
        if(fd<0)
        {
        printf("open html file failure\n");
        return -1;
        }
        rev=read(fd,html_content,sizeof(html_content));
        if(rev<0)
        {
        printf("read error\n");
        close(client_fd);
        exit(1);
        }
        //send to client
        send(client_fd,html_content,sizeof(html_content),0);
        printf("send to client\n");
        close(client_fd);
        }
        //close
        close(client_fd);
        close(server_fd);
        
        return 0;
}
        

编译运行结果:

强制将80端口绑定给服务,运行命令:sudo ./server

在浏览器输入我们写的服务器IP,进行连接

可查看该界面的html源码是否是我们服务器传过来的html.txt的源码,查看结果如下图

到此一个简单的http服务器就完成了。

基于例子1可以:1,扩展我们的服务器程序,支持我们自定义语法
2,是不是用于多线程来改善我们的服务器效率
3,还有继续优化的空间及思路。

发布了50 篇原创文章 · 获赞 13 · 访问量 1823

猜你喜欢

转载自blog.csdn.net/weixin_38251305/article/details/104065130