php - Why is the socket connection reset?
某草草
某草草 2017-05-16 13:00:37
0
1
583

Write your own http server, the server listens to the socket, and the handle_request thread handles the browser PHP dynamic requests.

 ...
    
    while(1){
        if(-1 == (client_fd = accept(sockfd, (struct sockaddr *) &client_sock, &sin_size))) err_exit("accept");
        if(pthread_create(&ntid, NULL, (void *)handle_request, &client_fd) != 0) err_exit("pthread_create");
    }
    close(sockfd);
    return 0;

After communicating with php-fpm in handle_request, I obtained the execution result msg. msg contains two lines of http response header information, a blank line and the response body (the result of php code execution), and then I only need to add a response line , an http response packet is constructed and finally sent to the client.

 ...
    
    /* Send response */
    sprintf(header, "%s 200 OK\r\n", hr->version);
    
    //printf("%s%s\n", header, msg);

    send(client_fd, header, strlen(header), 0);
    send(client_fd, msg, contentLength, 0);

    free(msg);
    close(client_fd);

The strange thing is that when I access it in the browser, the php execution results flash past, and then it prompts that the connection has been reset

Firefox can’t establish a connection to the server at 127.0.0.1:8899.

When tested on telnet, a complete http response message can be received

Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
GET /index.php HTTP/1.1
HTTP/1.1 200 OK
X-Powered-By: PHP/5.5.9-1ubuntu4.21
Content-type: text/html

hello worldConnection closed by foreign host.

php program

<?php
    echo "hello world";
某草草
某草草

reply all(1)
世界只因有你

Your design problem is very serious. You must &client_fd传到pthread_create很可能会引起连接丢失,因为你无法保证handle_request在下一个accpetimplement it before it succeeds. Another problem is that your design is terrible. If nothing else, at least the entire thread pool will be affected...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template