php - socket連線被重置是什麼原因 ?
某草草
某草草 2017-05-16 13:00:37
0
1
471

自己寫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 程式

某草草
某草草

全部回覆 (1)
世界只因有你

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

    最新下載
    更多>
    網站特效
    網站源碼
    網站素材
    前端模板
    關於我們 免責聲明 Sitemap
    PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!