首页  >  问答  >  正文

php - socket连接被重置是什么原因 ?

自己写http服务器, 服务端监听套接字, handle_request线程处理浏览器php动态请求.

    ...
    
    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;

在handle_request中与php-fpm通信之后, 获取了执行结果msg,  msg包含了两行http响应头信息, 空行 以及响应主体(php代码执行后的结果), 然后我只要添上一个响应行, 就构造了http响应数据包, 最后发给客户端.

    ...
    
    /* 发送响应 */
    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);

奇怪的是我在浏览器中访问, php执行结果一闪而过, 然后提示连接被重置

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

在telnet测试, 能收到完整的http响应信息

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 程序

<?php
    echo "hello world";
某草草某草草2689 天前509

全部回复(1)我来回复

  • 世界只因有你

    世界只因有你2017-05-16 13:02:37

    你这个设计问题很严重,你将&client_fd传到pthread_create很可能会引起连接丢失,因为你无法保证handle_request在下一个accpet成功之前一定先执行,还有一个问题就是,你的这个设计很烂,不说别的,最起码得整个thread pool吧……

    回复
    0
  • 取消回复