It is normal to write a socket client program to access it. It is also normal to use telent to access it, but when the browser accesses it as a client, it directly reports an error and does not enter the while loop at all. Why is this?
Browser access 127.0.0.1:8899
The server program exited directly and reported an error: Segmentation fault (core dumped)
The server code probably looks like this
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);
/*The browser will not execute this step at all, other clients will work normally*/
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;
}
过去多啦不再A梦2017-05-16 13:05:22
The browser uses the http protocol and the socket generally uses the tcp/ip protocol
The http protocol has a special header. Without it, of course it cannot be accessed