Send all available data in one chunk within the send handler. This improves speed.

This commit is contained in:
lotodore
2009-06-08 21:54:24 +00:00
parent e53c60c263
commit 938d13e31a
+34 -8
View File
@@ -44,10 +44,15 @@ class SendDataManager : public boost::enable_shared_from_this<SendDataManager>
{ {
public: public:
SendDataManager(boost::shared_ptr<boost::asio::ip::tcp::socket> s) SendDataManager(boost::shared_ptr<boost::asio::ip::tcp::socket> s)
: socket(s), writeInProgress(false) : socket(s), sendBuf(NULL), writeInProgress(false)
{ {
} }
~SendDataManager()
{
delete[] sendBuf;
}
void HandleWrite(const boost::system::error_code &error); void HandleWrite(const boost::system::error_code &error);
void AsyncSendNextPacket(bool handlerMode = false); void AsyncSendNextPacket(bool handlerMode = false);
@@ -56,6 +61,7 @@ class SendDataManager : public boost::enable_shared_from_this<SendDataManager>
mutable boost::mutex dataMutex; mutable boost::mutex dataMutex;
SendDataList list; SendDataList list;
char *sendBuf;
bool writeInProgress; bool writeInProgress;
}; };
@@ -64,7 +70,8 @@ void
SendDataManager::HandleWrite(const boost::system::error_code &error) SendDataManager::HandleWrite(const boost::system::error_code &error)
{ {
// TODO error handling // TODO error handling
AsyncSendNextPacket(true); if (!error)
AsyncSendNextPacket(true);
} }
void void
@@ -73,15 +80,34 @@ SendDataManager::AsyncSendNextPacket(bool handlerMode)
boost::mutex::scoped_lock lock(dataMutex); boost::mutex::scoped_lock lock(dataMutex);
if (!writeInProgress || handlerMode) if (!writeInProgress || handlerMode)
{ {
if (handlerMode) delete[] sendBuf;
list.pop_front(); sendBuf = NULL;
if (!list.empty())
unsigned bufPos = 0;
unsigned bufSize = 0;
// Count required bytes.
SendDataList::iterator i = list.begin();
SendDataList::iterator end = list.end();
while (i != end)
{ {
boost::shared_ptr<NetPacket> nextPacket = list.front(); bufSize += (*i)->GetLen();
++i;
}
if (bufSize)
{
sendBuf = new char[bufSize];
i = list.begin();
end = list.end();
while (i != end)
{
memcpy(sendBuf + bufPos, (*i)->GetRawData(), (*i)->GetLen());
bufPos += (*i)->GetLen();
++i;
}
list.clear();
boost::asio::async_write( boost::asio::async_write(
*socket, *socket,
boost::asio::buffer(nextPacket->GetRawData(), boost::asio::buffer(sendBuf, bufSize),
nextPacket->GetLen()),
boost::bind(&SendDataManager::HandleWrite, shared_from_this(), boost::bind(&SendDataManager::HandleWrite, shared_from_this(),
boost::asio::placeholders::error)); boost::asio::placeholders::error));
writeInProgress = true; writeInProgress = true;