寫一個socket客戶端程式存取正常. 用telent存取也正常, 但是瀏覽器作為客戶端訪問直接報錯, 壓根不會進入while循環中, 這是為啥 ?
瀏覽器存取 127.0.0.1:8899
服務端程式直接退出, 報了一行錯誤 : Segmentation fault (核心已轉儲)
服務端程式碼大概長下面這樣
int main(int argc, char *argv[]){
if(argc != 2){
err_msg("Usage: ./studyHttpd <ip address>\n");
}
struct sockaddr_in server_sock, client_sock;
int sockfd, client_fd;
int sin_size;
pthread_t ntid;
if(-1 == (sockfd = socket(AF_INET, SOCK_STREAM, 0))) err_exit("socket");
printf("Socket id = %d\n", sockfd);
server_sock.sin_family = AF_INET;
server_sock.sin_port = htons(PORT);
server_sock.sin_addr.s_addr = INADDR_ANY;
bzero(&(server_sock.sin_zero), 8);
int i = 1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
if(-1 == bind(sockfd, (struct sockaddr *)&server_sock, sizeof(struct sockaddr))) err_exit("bind");
printf("Bind success\n");
if(-1 == listen(sockfd, MAX_QUE_CONN_NM)) err_exit("listen");
printf("Listening port = %d\n", PORT);
sin_size = sizeof(client_sock);
/*在浏览器根本不会执行到这一步, 其他做客户端正常*/
while(1){
if(-1 == (client_fd = accept(sockfd, (struct sockaddr *) &client_sock, &sin_size))) err_exit("accept");
if(pthread_create(&ntid, NULL, (void *)handle, &client_fd) != 0) err_exit("pthread_create");
}
close(sockfd);
return 0;
}
瀏覽器走的是http協定 socket一般走的是tcp/ip協定
http協定有特殊的報文頭,沒有的話當然訪問不了