2
我正在爲web服務器編寫代碼,並試圖通過TCP套接字發送名爲index.html的html文件。我將如何做到這一點?如何通過TCP套接字讀取併發送html文件?
目前我正在嘗試讀取文件的內容,然後通過連接發送它們。但是,頁面未被正確接收。我懷疑我正在使用錯誤的函數來閱讀。但我不確定還有什麼要做的= s。請幫忙!
在代碼結束時,我正在關閉並清除所有文件和緩衝區。
while(!feof(sendFile)){
fgets(send_buffer, MAX_LEN, sendFile);
send(new_fd,send_buffer,sizeof(send_buffer),0);
}
這是我試圖實現的功能。這只是返回HTTP 404錯誤頁面:前
} else {
len = strlen("HTTP/1.1 404 Not Found\n");
send(new_fd, "HTTP/1.1 404 Not Found\n", len, 0);
send(new_fd,"Connection: Keep Alive\n",strlen("Connection: Keep Alive\n"),0);
send(new_fd,"Content-Type: html\n",strlen("Content-Type: html\n"),0);
//read and send the contents of the 404.html file
//open file
if((sendFile = fopen("404.html","r"))<0){
printf("FILE DID NOT OPEN!\n");
exit(1);
}
//obtain file size
fseek (sendFile , 0 , SEEK_END);
Fsize = ftell (sendFile);
rewind (sendFile);
/* // allocate memory to contain the whole file:
send_buffer = (char*) malloc (sizeof(char)*Fsize);
if(send_buffer == NULL){
printf("Memory error");
exit (1);
}
// copy the file into the buffer:
result = fread (send_buffer,1,Fsize,sendFile);
if(result != Fsize) {
printf("Reading error");
exit (1);
}
*/
send(new_fd,"Content-Length: ",strlen("Content-Length: "),0);
send(new_fd,int(Fsize),4,0); //this line is causing errors!!!!
send(new_fd,"\n",strlen("\n"),0);
while(!feof(sendFile)){
bzero(send_buffer,MAX_MSG);
fgets(send_buffer, sizeof(send_buffer), sendFile);
//result = send(new_fd,send_buffer,strlen(send_buffer),0);
if(send(new_fd,send_buffer,sizeof(send_buffer),0)!=sizeof(send_buffer)){
printf("Sending 404.html Failed\n");
break;
}
}
fclose(sendFile);
printf("Sent file\n");
}
} else if(strcmp(request_page, POST)==0){
// THIS IS WHERE YOU CAN TACKLE POST MESSAGES
}
我用fread努力,但編譯器口口聲聲說「稱爲對象的fread不是一個函數」。我已經包含了加上庫。這是我試圖實現的功能之一。頭文件發送正常。除了我不確定如何在不讀取整個文件的情況下發送Content-Length頭,也不知道如何將其包含在send()中。 –
BAkz
2010-09-10 02:29:51
好吧,我剛剛得到它的工作。我使用fread作爲文件描述符來打開文件。哎呦! – BAkz 2010-09-10 03:40:29
您可以使用fseek()和ftell()函數來確定文件的大小,而無需讀取文件內容。在發送實際文件內容之前,您必須發送所有HTTP標頭,包括Content-Length。你必須從文件send()中分別發送()頭文件。 – 2010-09-10 20:49:36