preface

And all the time, The understanding of Socket has always been in a very simple understanding of the level, has been unable to establish a connection between TCP and HTTP, one day accidentally found that VLC can actually send video from the computer to the mobile phone, so I looked at the CODE of VLC, found that it is to use CocoaHttpServer to achieve, is on the mobile phone to open a server, The video is then sent via a browser to the phone, which is then played back using VLC’s own player. CocoaHttpServer

process

CocoaHttpServer code to read or more laborious, so I want to own a simple implementation of a Server to help me read the code, in all aspects of the information after the code is as follows, here does not introduce socket programming each function, there are many good articles on the Internet, just put the whole generation Code.

#include "httpServer.h"
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>


#define SOCKET_PORT 8081

void startHttpServer(void){
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in server_addr;
    bzero(&server_addr, sizeof(struct sockaddr_in));
    server_addr.sin_family  =  AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(SOCKET_PORT);
    
    bind(fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    listen(fd, 5);
    
    int client_fd = accept(fd, NULL.NULL);
    char buff[1024];
    read(client_fd, buff, sizeof(buff));
    
    printf("%s\r\n", buff);
    
    char data[] = "HTTP/1.0 200 OK\r\nServer: DWBServer\r\ ncontent-type: text/ HTML; Charset = utF-8 \r\n\r\n< HTML >
      
C language implementation simple HttpServer
"
; write(client_fd, data, sizeof(data)); close(client_fd); close(fd); } Copy the code

Running effect

You can access our enabled service directly from your browser, but only on the same wifi.

conclusion

In fact, HTTP protocol, according to the established rules of the concatenation of content, and then the client (browser) according to the established rules to parse, there is no mystery. And recently when looking at the source code of MacOverview, the deepest experience is also in accordance with the established rules to resolve, this is the “protocol “.