我正在实施微型服务器,并且无法检测客户端请求。该要求要求我们只接受客户的请求,如果有两个连续的CRLF。所以我目前的代码是:
int bytes_read = recv(client, buffer, sizeof(buffer), 0);
if (bytes_read < 0) {
printfError("Problem with recv call", false);
}
if(checkRequest(buffer)) {
// Accept client's request
}
在我的checkRequest中,我将检查客户端的请求方法,文件名和HTTP:
bool checkRequest(char *buff, int &valid, int &ext) {
char *request_method = strtok(buff, " ");
char *request_filename = strtok(NULL, " ");
char *request_http = strtok(NULL, " ");
int i;
bool isValid = false;
for(i = 0; i < 2; i++) {
if(*request_http == '\r') {
isValid = true;
*request_http++;
if(*request_http == '\n') {
// Keep checking
*request_http++;
} else {
isValid = false;
}
}
if(!isValid) break; // Not 2 consecutive CRLFs;
}
return isValid;
我在telnet上测试时遇到的问题是当我点击第一个输入时;它只能检测到第一个crlf。我也尝试在while循环之间的recv()但它会卡在里面。
答案 0 :(得分:1)
虽然有更全面,更健壮的方法来实现这一目标,但这是解决您问题的简单方法。从来没有保证从发件人调用中收到多少字节,因此您必须继续调用recv,直到您获得了预期的数据量。
const unsigned int kuiBytesExpected = 4;
unsigned int uiBytesReceived = 0;
while ( uiBytesReceived < kuiBytesExpected )
{
int bytes_read = recv(client, buffer + uiBytesReceived, kuiBytesExpected - uiBytesReceived, 0);
// recv returns 0 if client disonnects and -1 on error
if ( bytes_read < 1 )
{
printfError("Problem with recv call", false);
break;
}
else
{
uiBytesReceived += bytes_read;
}
}
if ( uiBytesReceived == kuiBytesExpected )
{
if(checkRequest(buffer))
{
// Accept client's request
}
}