Adaptation of the HttpServer by user yueee_yt. This version has improved handling of the HTTP headers (**NOTE**: There are limitations with this implementation and it is not fully functional. Use it only as a starting point.)
Dependents: DMSupport DMSupport DMSupport DMSupport
Fork of DM_HttpServer by
Diff: HTTPRequestHandler.cpp
- Revision:
- 8:5779cee2e94a
- Parent:
- 6:7b3320c34654
- Child:
- 9:10b4d4075fbb
diff -r ee7af5de4b95 -r 5779cee2e94a HTTPRequestHandler.cpp --- a/HTTPRequestHandler.cpp Wed Dec 03 13:34:20 2014 +0000 +++ b/HTTPRequestHandler.cpp Mon Dec 08 12:49:53 2014 +0000 @@ -149,7 +149,13 @@ static char line[128]; static char key[128]; static char value[128]; - while( readLine(line, 128) > 0) { //if == 0, it is an empty line = end of headers + + // Prepare cache + read_cache_t* cache = (read_cache_t*)malloc(sizeof(read_cache_t)); + cache->size = 1024; + cache->num = cache->pos = 0; + + while( readLineCached(line, 128, cache) > 0) { //if == 0, it is an empty line = end of headers int n = sscanf(line, "%[^:]: %[^\n]", key, value); if ( n == 2 ) { #ifdef _DEBUG_REQUEST_HANDLER @@ -159,6 +165,7 @@ } //TODO: Impl n==1 case (part 2 of previous header) } + free(cache); } void HTTPRequestHandler::writeHeaders() //Called at the first writeData call @@ -205,6 +212,51 @@ *str = 0; return len; } + + +int HTTPRequestHandler::readLineCached(char* str, int maxLen, read_cache_t* cache) +{ + maxLen--; // leave room for null termination + + int len = 0; + int i = 0; + bool found = false; + while (i < maxLen && !found) { + if (cache->num <= cache->pos) { + // get something to process + int ret = m_pTCPSocketConnection->receive(cache->buff, cache->size); + if(ret == -1) { + // error + break; + } else if (ret == 0) { + // didn't get anything to process, try again + continue; + } + cache->num = ret; + cache->pos = 0; + } + + // have >0 bytes to process + while ((cache->pos < cache->num) && (i < maxLen)) { + *str = cache->buff[cache->pos++]; + if( (len > 1) && *(str-1)=='\r' && *str=='\n' ) { + str--; + len-=2; + found = true; + break; + } else if( *str=='\n' ) { + len--; + found = true; + break; + } + str++; + len++; + } + } + *str = 0; + return len; +} + /** void HTTPRequestHandler::onTCPSocketEvent(TCPSocketEvent e) {