【发布时间】:2018-05-13 23:43:16
【问题描述】:
我已经用 C 语言实现了基本的 Web 服务器,它服务于来自客户端的 GET 请求。问题是它不发送 HTML 页面。
while(1){
if((temp_sock[id] = accept(sockfd, (t_sockaddr*)address, &address_size))==-1){
perror("Accepting Failure: ");
pthread_mutex_lock(&lock);
fprintf(logfile, "Accepting error: %d\n", localfd);
pthread_mutex_unlock(&lock);
exit(1);
}
else{
pthread_mutex_lock(&lock);
fprintf(logfile, "\nAccepting Success");
pthread_mutex_unlock(&lock);
}
if (temp_sock[id]> 0){
pthread_mutex_lock(&lock);
fprintf(logfile, "\nClient is connected");
pthread_mutex_unlock(&lock);
}
recv(temp_sock[id] , buf, buffsize, 0);
pthread_mutex_lock(&lock);
fprintf(logfile, "\nyou recieved : %s\n ", buf);
pthread_mutex_unlock(&lock);
if((resource=analyze(buf))==NULL){ /*analyze - implements basic security and searches files on a disc*/
printf("\nres is NULL");
write(temp_sock[id], "HTTP/1.1 200 OK\n", 16);
write(temp_sock[id], "Content-length: 50\n", 19);
write(temp_sock[id], "Content-Type: text/html\n\n", 25);
write(temp_sock[id], "<html><body><H1>404 Not Found</H1></body></html>", 50);
}
else{
while(fgets(message, 150, resource)!=NULL){
write(temp_sock[id], "HTTP/1.1 200 OK\n", 16);
write(temp_sock[id], "Content-length: 151\n", 19);
write(temp_sock[id], "Content-Type: text/html\n\n", 25);
write(temp_sock[id], message, 151); //here problems start
}
fclose(resource);
}
close(temp_sock[id]);
}
}
这只是接受一个线程的循环,我没有发布整个代码,因为在我想要发送包含多行文本的页面(例如维基百科文章)之后一切正常读取文件网络服务器刚刚停止。但是如果文件只包含
<html><body><H1>Hello! How are you?</H1></body></html>
服务器以正确的方式发送它。 提前致谢。
【问题讨论】: