服务器问题记录
针对向我一样C++初学者,Quill Plan 由浅入深,慢慢剖析服务器编程。
项目地址 : https://github.com/PushedChris/-Quill-Plan-
错误描述:解析http报文时,当使用get方式传输或者使用post字段并且content-lenght = 0时,服务器运行正常,而当使用post字段并且content-lenght 部位0时,服务器解析http出错,下面贴出这部分源代码:
/*prase header*/
while(m_read_buf[0] != '\n' && m_read_buf[1] != '\n'){
int len = Readline(m_sockfd,m_read_buf,MAXLINE);
char *text = m_read_buf;
if(strncasecmp(text, "Range:", 6) == 0){
sscanf(text, "Range: bytes=%lu-%lu", &offset, &end);
// Range: [start, end]
if(end != 0) end ++;
}else if(strncasecmp(text, "Content-length:", 15) == 0){// important ==> lens
text[len] = '\0';
text += 15;
text += strspn(text, " \t");
m_content_length = atol(text);
}
}
/*prase_content*/
if(m_content_length > 0){
int len = Readline(m_sockfd,m_read_buf,MAXLINE);
m_read_buf[len] = '\0';
printf("content is %s", m_read_buf);
}
代码解释
使用readline函数解析http报文,当m_read_buf[0] != '\n' && m_read_buf[1] != '\n'
时,读到 \r\n
,这时可以对post内容进行读取
char name[100], password[100];
int i;
for (i = 5; m_read_buf[i] != '&'; ++i)
name[i - 5] = m_read_buf[i];
name[i - 5] = '\0';
int j = 0;
for (i = i + 10; m_read_buf[i] != '\0'; ++i, ++j)
password[j] = m_read_buf[i];
password[j] = '\0';
读取name、password正确,但是会出现html页面的跳转错误,再表单提交后,需要跳转到index.html页面,但错误跳转到了log页面(即原页面)
172.31.129.193:8044 200 - root/log.html
accept request, fd is 5, pid is 22215
data is POST /4 HTTP/1.1
问题解决
不能使用readline 而只能使用readn
/*prase_content*/
if(m_content_length > 0){
int len = Readn(m_sockfd,m_read_buf,m_content_length);
m_read_buf[len] = '\0';
printf("content is %s", m_read_buf);
}