Starting from zero an HTTP server-start (i)

Source: Internet
Author: User
Tags htons

Starting from zero an HTTP server (one)

Code Address: Https://github.com/flamedancer/cserver
git checkout Step1

A simple socket server
    • Starting from HelloWorld
    • Recalling the C language socket communication
    • A simple socket server
    • Test with Telent
Starting from HelloWorld

First to review the C language, C language Helloword program is as follows

// main.c#include<stdio.h>int main() {    printf("hello world");}

Compiling GCC main.c
Run./a.out
Output Hello World

Review the general steps of socket (server side) communication for the C language
* 创建 socket , 返回socket 文件描述符,需指明域(本地文件socket还是网络socket),类型(TCP 还是 UDP)* 绑定 bind, 绑定socket地址(本地socket文件地址 或 网络地址 IP + port) * 监听 listen, 为socket创建监听队列, 连接到socket的链接将会进入这个队列, 需要指明队列最大长度* 接收链接 accept, 接收客户端链接,返回接收到的 客户socket文件描述符* 读写  read/write,  对 客户socket文件描述符 进行 读写操作来进行通信* close, 通信结束, 关闭 客户socket文件描述符, 整个server结束,也要关闭 server socket文件描述符
Functions and structure prototypes for C-language socket communication
    1. Creating a Socket
    #include <sys/types.h> #include <sys/socket.h>    int socket(int domain, int type, int protocol);     *** domains             AF_UNIX: 本地文件socket (file system sockets)                          AF_INET: 网络socket (UNIX network sockets)             ...     *** type             SOCK_STREAM: TCP 协议              SOCK_DGRAM: UDP 协议     *** protocol          一般选默认值 0
    1. Struct:socket Address Socket Structure body
      Local File Socket address:
    AF_UNIX socket_un    defind in sys/un.h       struct sockaddr_un {           sa_family_t sun_family; // AF_UNIX           char sun_path[]; // pathname       };     网络socket 地址:    AF_INET sockaddr_in   defind in netinet/in.h        struct sockaddr_in {            short int sin_family;  // AF_INET            unsigned short in sin_port;   // Port number            struct in_addr sin_addr;  // Inernet address        };        其中代表ip地址的结构体in_addr:        struct in_addr {            unsigned long int s_addr;        }
    1. Bind
      Successful return 0, failure return-1, failure information see errno
    #include <sys/socket.h>    int bind(int socket, const struct sockaddr *address, size_t address_len);
    1. Creating a socket queue
    #include <sys/socket.h>    int listen(int socket, int backlog);  // backlog : the maximum number of pending connections
    1. Accept connections
      Address and Address_len here refer to the client-side addresses, and if the client is successfully connected, address is populated
      Returns the socket file descriptor of the client after the connection
    #include <sys/socket.h>    int accept(int socket, struct sockaddr *address, size_t *address_len);
    1. Host and Network Byte ordering
      It is possible that the local byte encoding order differs from the network byte encoding order, and the local byte encoding is converted to network byte encoding
    #include <netinet/in.h>    unsigned long int htonl(unsigned long int hostlong);    unsigned short int htons(unsigned short int hostshort);
A simple socket server
#include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <netinet/in.h># Include <arpa/inet.h> #include <unistd.h> #include <netinet/in.h>int main () {int SERVER_SOCKFD, Clien    T_SOCKFD;    int Server_len, Client_len;    struct sockaddr_in server_address;    struct sockaddr_in client_address; SERVER_SOCKFD = socket (af_inet, sock_stream, 0);    Create socket, select address type for network address, select TCP Communication server_address.sin_family = af_inet;  SERVER_ADDRESS.SIN_ADDR.S_ADDR = inet_addr ("127.0.0.1");    Set the IP of the network address, INET_ADDR automatically to the network byte order Server_address.sin_port = Htons (9734);    Set the port number, note here the Htons method Server_len = sizeof (server_address);    Bind (SERVER_SOCKFD, (struct sockaddr *) &server_address, Server_len);    Listen (SERVER_SOCKFD, 5);        while (1) {char ch[5000];  Char send_str[] = "Hello World!\n";        The string client_len = sizeof (client_address) to be sent to the connected client; CLIENT_SOCKFD = Accept (SERVER_SOCKFD, (Struct SOCKADDR *) &client_address, &client_len);    Read (CLIENT_SOCKFD, &ch, 5000);     Receive the characters that came from the client printf ("%s", ch);   Print the characters we receive write (CLIENT_SOCKFD, &send_str, sizeof (SEND_STR)/sizeof (send_str[0]));    Send data to the client, there is no difference between read write and file read and write close (CLIENT_SOCKFD); }}

Compile and run our first version as before Helloword!

Test with Telnet

Look at the effect! City a terminal, and then use Telnet to try to connect to our server.
Execute command telnet 127.0.0.1 9734
Enter a few characters at random press ENTER
The screen output is about this:

Trying 127.0.0.1...Connected to localhost.Escape character is '^]'.dsfsdhello world !Connection closed by foreign host.

Back to view our server screen printing, we can see the characters we just randomly entered, indicating that our server can successfully receive and return data.

Starting from zero an HTTP server-start (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.