首頁  >  問答  >  主體

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 天前508

全部回覆(1)我來回復

  • 世界只因有你

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

    你這個設計問題很嚴重,你將&client_fd传到pthread_create很可能会引起连接丢失,因为你无法保证handle_request在下一个accpet成功之前一定先執行,還有一個問題就是,你的這個設計很爛,不說別的,最起碼得整個thread pool吧…

    回覆
    0
  • 取消回覆