这几天学的有点多啊,先来上图:

httpserver

info

参考了这篇干货:Linux的SOCKET编程详解

代码

/*************************************************************************
    > File Name: hello_server.cpp
      > Author: Netcan
      > Blog: http://www.netcan666.com
      > Mail: 1469709759@qq.com
      > Created Time: 2016-02-19 五 13:23:17 CST
 ************************************************************************/

#include <iostream>
#include <errno.h>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
using namespace std;
#define PORT 8080 // 端口

int main() {
    int socket_fd, connect_fd; // 服务器socket,客户端连接socket
    struct sockaddr_in serveraddr; // 服务器地址

    if((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { // TCP,三次握手。
        printf("create socket error: %s\n", strerror(errno));
        exit(0);
    }
    memset(&serveraddr, 0, sizeof(serveraddr));

    serveraddr.sin_family = AF_INET; // IPV4
    serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); // 0.0.0.0
    serveraddr.sin_port = htons(PORT); // 主机字节码 => 网络字节码

    if(bind(socket_fd, (sockaddr*)&serveraddr, sizeof(serveraddr)) == -1) {
        printf("bind socket error: %s\n", strerror(errno));
        exit(0);
    }

    if(listen(socket_fd, 100) == -1) { // 监听,最大连接数
        printf("listen socket error: %s", strerror(errno));
        exit(0);
    }

    // HTTP
    const char status[] = "HTTP/1.0 200 OK\r\n";
    const char header[] = "Server: Netcan Web Server\r\nContent-Type: text/html\r\n\r\n";
    const char body[] = "<html><title>Hello World!</title></head><body><h2>Hello World!</h2></body></html>";

    while(true) {
        if((connect_fd = accept(socket_fd, (sockaddr*)NULL, NULL)) == -1) { // 阻塞进程
            printf("accept socket error: %s\n", strerror(errno));
            continue;
        }

        // 回应数据
        if(!fork()) {
            send(connect_fd, status, sizeof(status), 0);
            send(connect_fd, header, sizeof(header), 0);
            send(connect_fd, body, sizeof(body), 0);
            exit(0);
        }
        close(connect_fd);
    }
    close(socket_fd);
    return 0;
}