我用C语言编写了一个web服务器,根据URL中提供的请求,web服务器完全成功地检索到了相关的网页!下面是处理URL请求的代码部分!
if ( strncmp(reqline[1], "/\0", 2)==0 )
reqline[1] = "/index.html";
//If no file is specified, index.html will be opened by default
strcpy(path, ROOT);
strcpy(&path[strlen(ROOT)], reqline[1]);
printf("file: %s\n", path);
if ( (fd=open(path, O_RDONLY))!=-1 ) //If a html file is found
{
send(clients[n], "HTTP/1.0 200 OK\n\n", 17, 0);
while ( (bytes_read=read(fd, data_to_send, BYTES))>0 )
write (clients[n], data_to_send, bytes_read);
}
else { //If html file not found
write (clients[n], "File not found", 15);
}
当用户提供一个不存在的404error.html
文件的网址而不是当前显示的文本“找不到文件”时,我想要显示我的index.html网页(在有html和其他html网页的文件夹中找到)。
发布于 2018-06-02 03:50:41
我不能编译或运行不完整的代码,但如果没有找到请求的文件,“猜测”将发送错误通知文件。"404error.html“文件必须存在于可用路径上。
if ( (fd=open(path, O_RDONLY))!=-1 ) { // If the file is found
send(clients[n], "HTTP/1.0 200 OK\n\n", 17, 0);
while ( (bytes_read=read(fd, data_to_send, BYTES))>0 )
write (clients[n], data_to_send, bytes_read);
close(fd); // add this
}
else if ( (fd=open("404error.html", O_RDONLY))!=-1 ) { // Send the error file
send(clients[n], "HTTP/1.0 200 OK\n\n", 17, 0);
while ( (bytes_read=read(fd, data_to_send, BYTES))>0 )
write (clients[n], data_to_send, bytes_read);
close(fd); // add this
}
else {
write (clients[n], "File not found", 15); // tough luck, back to to you
}
我不知道clients[n]
是什么,但你肯定知道。
源代码可以通过不重复传输代码来提高效率,但我将这留给您。这个答案是一个想法。
https://stackoverflow.com/questions/50649709
复制相似问题