void receiveRequest(int clientSockfd, string dir){ // read/write data from/into the connection bool isEnd = false; char buf[1000] = { 0 }; stringstream ssOverall; stringstream ssIteration; const string endingStr = "\r\n\r\n"; unsigned int endingCount = 0; while (!isEnd) { memset(buf, '\0', sizeof(buf)); if (recv(clientSockfd, buf, 1000, 0) == -1) { perror("recv"); return;// 5; } ssOverall << buf; ssIteration << buf; string currString = ssIteration.str(); for(unsigned int i = 0; i < currString.length(); i++){ if(currString[i] == endingStr[endingCount]) endingCount++; else endingCount = 0; if(endingCount == 4){ string totalReqString = ssOverall.str(); // cout << "--------totalReqString--------" << endl << totalReqString << endl; vector<uint8_t> decoded(totalReqString.begin(), totalReqString.end()); HttpRequest req = HttpRequest::decode((ByteBlob)decoded); HttpResponse resp = processRequest(req, dir); //Process the request object ByteBlob respBB = resp.encode(); uint8_t* respBytes = &respBB[0]; int respBytesSize = sizeof(uint8_t) * respBB.size(); // cout << "Num bytes being sent total: " << respBB.size() << endl; // cout << "Num bytes being sent, data: " << resp.getData().size() << endl; std::ofstream os("asdfasdfasdf.jpg"); if (!os) { std::cerr<<"Error writing to ..."<<std::endl; } else { HttpResponse decodedResp = HttpResponse::decode(respBB); // ByteBlob data = resp.getData(); ByteBlob data = decodedResp.getData(); for(ByteBlob::iterator x=data.begin(); x<data.end(); x++){ os << *x; } os.close(); } if (send(clientSockfd, respBytes, respBytesSize, 0) == -1) { perror("send"); return;// 6; } //ssOverall.str(""); doesn't matter, we're closing connection //endingCount = 0; isEnd = true; break; } } } close(clientSockfd); cout << "Server closing" << endl;; }