Moment For Technology

The HTTP server is set up on the Linux socket to display images

Posted on Nov. 26, 2023, 12:13 p.m. by Stephanie Caldwell-Webster
Category: The back-end Tag: linux The back-end TCP/IP Network protocol

This paper is participating in theNetwork protocols must be known and must be known"Essay campaign

1. Introduction

This article as Linux socket(TCP) network programming practice, using C language code to build a simple HTTP server, complete the interaction with the browser, and finally display a picture on the browser; Through this example can consolidate the socket multi-threaded use, but also easy to learn to understand the HTTP protocol.

2. HTTP protocol introduction

HTTP itself is based on THE TCP communication protocol to transfer data (HTML files, image files - also called hypertext transfer protocol), HTTP must work on the client-server architecture (itself is TCP), HTTP default port number 80(browser access default port 80). But you can change it to 8080 or another port (you can specify the port manually).

The HTTP protocol is connectionless, which limits processing to one request per connection; The server disconnects from the customer after processing the request and receiving the reply from the customer. In this way, transmission time can be saved.

3. HTTP message structure

The request message sent by the client to the HTTP server consists of four parts: request line, request header, blank line, and request data

Here is a request from the browser to compare the format of the image above:

GET/HTTP/1.1 Host: Connection: keep-alive upgrade-insecure -Requests: 1 user-agent: Mozilla / 5.0 (Windows NT 10.0; Win64; X64) AppleWebKit (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml; Q = 0.9, image/avif, image/webp image/apng, * / *; Q = 0.8, application/signed - exchange; v=b3; Q =0.9 Accept-encoding: gzip, deflate Accept-language: zh-cn,zh; Q = 0.9Copy the code

The common HTTP requests are GET and POST.

HTTP1.0 defines three request methods: GET, POST, and HEAD.

HTTP1.1 adds five new request methods: OPTIONS, PUT, DELETE, TRACE, and CONNECT.

The HTTP server response to the client consists of four parts: the status line, the message header, the blank line, and the response body.

Such as:

"HTTP / 1.1 200 OK \ r \ n"
"... The body..."
Copy the code

Field meanings of the packets listed above:

HTTP/1.0 200 OK: HTTP/1.0 indicates that the protocol is HTTP. 1.0 is the protocol version. 200 means success

Content-type: tells the browser what type of data to send back

Content-length: tells the browser the size of the entity body in the packet, that is, the Length of the returned Content

There are several types of status codes in the above fields, respectively:

200 - Request successful

301 - Resources (web pages, etc.) are permanently transferred to another URL

404 - Requested resource (web page, etc.) does not exist

500 - Internal server error

4. HTTP interaction flow

The first request is made by an HTTP client (browser). The HTTP server receives the request, parses it, and then completes the subsequent interaction.

If you want to display an image on the browser, the interaction flows like this:

To get the browser to display an image in the interface, you have to write an HTML code to the browser that simply uses an image tag.

The HTML code used for the current program is relatively simple and is posted below:

        meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /
        centerimg src="www/123.jpg" width="512px" height="384px" /
Copy the code

Then you need to prepare a JPG image, as a resource file, easy to pass to the browser, the local file structure is as follows:

5. Case code: Set up HTTP server

The following code responds to a browser request in multithreaded form.

#include stdio.h
#include unistd.h
#include string.h
#include sys/types.h
#include sys/stat.h
#include fcntl.h
#include dirent.h
#include stdlib.h
#include pthread.h
#include semaphore.h
#include signal.h
#include sys/types.h
#include sys/socket.h
#include arpa/inet.h
#include netinet/in.h
#include pthread.h
/* The server sends response data to the client */
int HTTP_ServerSendFile(int client_fd,char *buff,char *type,char *file)
    /*1. Open file */
    int fd=open(file,2);
    if(fd0)return - 1;
    /*2. Obtain the file size */
    struct stat s_buff;
    /*3. Build the response header */
    sprintf(buff,"HTTP / 1.1 200 OK \ r \ n"
    /*4. Send the response header */
    if(write(client_fd,buff,strlen(buff))! =strlen(buff))return 2 -;
    /*5. Send message body */
    int cnt;
        if(write(client_fd,buff,cnt)! =cnt)return - 3;
        if(cnt! =1024)break;
    return 0;
/* Thread worker function */
void *thread_work_func(void *argv)
    int client_fd=*(int*)argv;
    unsigned int cnt;
    unsigned char buff[1024];
    // Read the data sent by the browser
    buff[cnt]='\ 0';
    if(strstr(buff,"The GET/HTTP / 1.1"))
    else if(strstr(buff,"GET/WWW / 123. HTTP / 1.1 JPG"))
    else if(strstr(buff,"The GET/favicon. Ico HTTP / 1.1"))
    // Exit the thread
int main(int argc,char **argv)
    if(argc! =2)
        printf("./app  port number \n");
        return 0;
    signal(SIGPIPE,SIG_IGN); // Ignore the SIGPIPE signal -- to prevent an unexpected server exit
    int sockfd;
    /*1. Create socket */
    int on = 1;
    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, on, sizeof(on));
    /*2. Bind the port number and IP address */
    struct sockaddr_in addr;
    addr.sin_port=htons(atoi(argv[1])); // The port number ranges from 0 to 65535
    addr.sin_addr.s_addr=INADDR_ANY;    / / inet_addr (" "); / / IP address
    if(bind(sockfd,(const struct sockaddr *)addr,sizeof(struct sockaddr))! =0)
        printf("Server: port number binding failed.\n");
    /*3. Set the number of listeners, which indicates the maximum number of connections that the server can process at a time */
    /*4. Wait for the client to connect */
    int *client_fd;
    struct sockaddr_in client_addr;
    socklen_t addrlen;
    pthread_t thread_id;
        addrlen=sizeof(struct sockaddr_in);
        *client_fd=accept(sockfd,(struct sockaddr *)client_addr,addrlen);
            printf("Client connection failed.\n");
            return 0;
        printf("Connected client IP address :%s\n".inet_ntoa(client_addr.sin_addr));
        printf("Connected client port number :%d\n".ntohs(client_addr.sin_port));
        /* Create thread */
            printf("Thread creation failed.\n");
        /* Sets the thread separation property */
    /*5. Close the connection
    return 0;
Copy the code

6. The effect of the final operation

About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.