C ++ Boost :: ASIO async_read的读取时间有所增加

时间:2014-04-08 04:24:41

标签: c++ boost boost-asio

我使用boost :: asio设置了一个C ++程序,将家庭网络中的两台计算机连接在一起。一个充当服务器,另一个充当客户端。客户端计算机将其播放器的数据(~50chars)传送到服务器,服务器吸引服务器计算机的播放器和客户端计算机的播放器。玩家是用箭头键移动的正方形。服务器计算机上的客户端方块严重滞后,但服务器方块的呈现方式与预期的完全相同。我输出了服务器对客户端数据的异步读取之间的时间,并且它显示读取通常需要大约1-4 ms,并且在大约十次读取之后,一次读取需要> 100ms,然后返回正常。我不知道这些跳过的来源。以下是我的TCPConnection读取方法:

void TCPConnection::readCycle() {
    if(!_socket.is_open())
        return;

    boost::asio::async_read(_socket, boost::asio::buffer(readBuf),
                            boost::bind(&TCPConnection::doneReading, shared_from_this(),
                                        boost::asio::placeholders::error,
                                        boost::asio::placeholders::bytes_transferred,
                                        true));
}

void TCPConnection::doneReading(boost::system::error_code error, size_t bytesTransfered, bool readAgain) {
    if(error == boost::asio::error::eof) {
        _socket.close();
        return;
    }

    double time = SDL_Millis();
    if(lastRead != 0)
        cout << "Time between reads (" << bytesTransfered << " bytes) : " << time - lastRead << endl;

    lastRead = time;

    _readData = string(readBuf.begin(), readBuf.begin() + bytesTransfered);

    if(readAgain) {
        boost::asio::async_read(_socket, boost::asio::buffer(readBuf),
                                boost::bind(&TCPConnection::doneReading, shared_from_this(),
                                            boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred,
                                            true));
    }
}

以下是一些示例输出:

Time between reads (128 bytes) : 3
Time between reads (128 bytes) : 159
Time between reads (128 bytes) : 4
Time between reads (128 bytes) : 3
Time between reads (128 bytes) : 3
Time between reads (128 bytes) : 3
Time between reads (128 bytes) : 6
Time between reads (128 bytes) : 4
Time between reads (128 bytes) : 3
Time between reads (128 bytes) : 3
Time between reads (128 bytes) : 4
Time between reads (128 bytes) : 5
Time between reads (128 bytes) : 154
Time between reads (128 bytes) : 4
Time between reads (128 bytes) : 3
Time between reads (128 bytes) : 6
Time between reads (128 bytes) : 3
Time between reads (128 bytes) : 3
Time between reads (128 bytes) : 4
Time between reads (128 bytes) : 6
Time between reads (128 bytes) : 4
Time between reads (128 bytes) : 3
Time between reads (128 bytes) : 3
Time between reads (128 bytes) : 7
Time between reads (128 bytes) : 6

0 个答案:

没有答案