Skip to content

Commit

Permalink
Stop streaming file is remote closes connection.
Browse files Browse the repository at this point in the history
  • Loading branch information
TautvydasZilys committed Dec 6, 2014
1 parent f0b058b commit 6ac76c3
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ void FileBrowserResponseHandler::Execute()
}
}

void FileBrowserResponseHandler::SendData(const char* data, size_t length) const
bool FileBrowserResponseHandler::SendData(const char* data, size_t length) const
{
Assert(length < static_cast<size_t>(numeric_limits<int>::max()));
auto sendResult = send(m_ClientSocket, data, static_cast<int>(length), 0);
Expand All @@ -51,6 +51,8 @@ void FileBrowserResponseHandler::SendData(const char* data, size_t length) const
{
Logging::Error(WSAGetLastError(), "Failed to send response: ");
}

return sendResult == static_cast<int>(length);
}

void FileBrowserResponseHandler::SendNotFoundResponse() const
Expand Down Expand Up @@ -141,12 +143,13 @@ void FileBrowserResponseHandler::StreamFile() const
char* volatile currentBuffer;
volatile int currentDataLength;
volatile bool doneReading = false;
volatile bool doneSending = false;
bool failed = false;

Event dataReadyEvent(false),
bufferPtrReadEvent(false);

thread sendingThread([this, &currentBuffer, &currentDataLength, &doneReading, &dataReadyEvent, &bufferPtrReadEvent]()
thread sendingThread([this, &currentBuffer, &currentDataLength, &doneReading, &doneSending, &dataReadyEvent, &bufferPtrReadEvent]()
{
for (;;)
{
Expand All @@ -162,7 +165,12 @@ void FileBrowserResponseHandler::StreamFile() const

bufferPtrReadEvent.Set();

SendData(dataPtr, currentDataLength);
if (!SendData(dataPtr, currentDataLength))
{
bufferPtrReadEvent.Set();
doneSending = true;
return;
}
}
});

Expand All @@ -181,6 +189,9 @@ void FileBrowserResponseHandler::StreamFile() const
if (!bufferPtrReadEvent.Wait(kTimeout)) // Throw exception if the other thread fails to second data within 30 seconds
throw exception(); // This usually happens when browser cancels download but doesn't close the socket

if (doneSending)
break;

currentBufferIndex = (currentBufferIndex + 1) % kBufferCount;
}
catch (exception)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class FileBrowserResponseHandler
FileBrowserResponseHandler(SOCKET clientSocket, const std::string& requestedPath, const std::string& httpVersion);
void Execute();

void SendData(const char* data, size_t length) const;
bool SendData(const char* data, size_t length) const;
void SendNotFoundResponse() const;

void SendFileResponse() const;
Expand Down

0 comments on commit 6ac76c3

Please sign in to comment.