【发布时间】:2011-01-25 16:43:23
【问题描述】:
我正在编写一个支持 HTTP 的基于 C 的服务器。 &buffer[5] 具有文件名。我在下一步设置标题,然后以 8Kb 的块发送文件。当我请求一个 txt 文件时它工作正常,但是当我请求一个 jpg 文件时,它没有提供任何 o/p。 我需要对图像文件采取什么特别的措施还是有其他问题。
void web(int fd)
{
int j, file_fd;
int buflen; int len;
long i, ret;
char * fstr;
static char buffer[BUFSIZE+1]; /* static so zero filled */
ret =read(fd,buffer,BUFSIZE); /* read Web request in one go */
if(ret == 0 || ret == -1) { /* read failure stop now */
//log1(SORRY,"failed to read browser request","",fd);
}
if(ret > 0 && ret < BUFSIZE) /* return code is valid chars */
buffer[ret]=0; /* terminate the buffer */
else buffer[0]=0;
for(i=0;i<ret;i++) /* remove CF and LF characters */
if(buffer[i] == '\r' || buffer[i] == '\n')
buffer[i]='*';
log1(LOG,"request",buffer,1);
if( strncmp(buffer,"GET ",4) && strncmp(buffer,"get ",4) )
log1(SORRY,"Only simple GET operation supported",buffer,fd);
for(i=4;i<BUFSIZE;i++) { /* null terminate after the second space to ignore extra stuff */
if(buffer[i] == ' ') { /* string is "GET URL " +lots of other stuff */
buffer[i] = 0;
break;
}
}
for(j=0;j<i-1;j++) /* check for illegal parent directory use .. */
if(buffer[j] == '.' && buffer[j+1] == '.')
log1(SORRY,"HTTP/1.0 400 Bad Request: Invalid URI: \n Parent directory (..) path names not supported",buffer,fd);
if( !strncmp(&buffer[0],"GET /\0",6) || !strncmp(&buffer[0],"get /\0",6) ) /* convert no filename to index file */
(void)strcpy(buffer,"GET /index.html");
/* work out the file type and check we support it */
buflen=strlen(buffer);
fstr = (char *)0;
for(i=0;extensions[i].ext != 0;i++) {
len = strlen(extensions[i].ext);
printf("%s\t%s\t%d\n", &buffer[buflen-len],extensions[i].ext, strncmp(&buffer[buflen-len], extensions[i].ext, len));
if( !strncmp(&buffer[buflen-len], extensions[i].ext, len)) {
fstr =extensions[i].filetype;
break;
}
}
if(fstr == 0)
log1(SORRY,"HTTP/1.0 400 Bad Request: Invalid URI:\n file extension type not supported",buffer,fd);
printf("Buffer Value: %s\n",&buffer[5]);
if(( file_fd = open(&buffer[5],O_RDONLY)) == -1) /* open the file for reading */
{
log1(SORRY, "HTTP/1.0 404 Not Found\n failed to open file",&buffer[5],fd);}
printf("file Descrptr:%d\n",file_fd);
log1(LOG,"SEND",&buffer[5],1);
(void)sprintf(buffer,"HTTP/1.0 200 OK\r\nContent-Type: %s\r\n\r\n", fstr);
(void)write(fd,buffer,strlen(buffer));
printf("Buffer Header:%s\n",buffer);
//int rec = read(file_fd, buffer, 10*BUFSIZE);
/* send file in 8KB block - last block may be smaller */
while ( (ret = read(file_fd, buffer, BUFSIZE)) > 0 ) {
(void)write(fd,buffer,ret);
printf("BufferData:%d\n",strlen(buffer));
}
#ifdef LINUX
sleep(1); /* to allow socket to drain */
#endif
exit(1);
}
o/p 用于 jpg 文件:
server: got connection from 127.0.0.1
Buffer Header:HTTP/1.0 200 OK
Content-Type: image/jpeg
BufferData:4
BufferData:95
BufferData:122
BufferData:24
BufferData:217
对于txt文件:
Buffer Value: config.txt
file Descrptr:4
Buffer Header:HTTP/1.0 200 OK
Content-Type: text/plain
BufferData:416
【问题讨论】:
标签: c network-programming