写一个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协议有特殊的报文头,没有的话当然访问不了