Boost ASIO套接字读取N个字节不多不少并等待它们到来或超时异常?

2024-01-05

创建一个简单的TCP服务器examples http://www.boost.org/doc/libs/1_43_0/doc/html/boost_asio/examples.html但仍然不知道如何创建一个可以读取一定数量字节的套接字,如果没有足够的字节则等待。我需要这不是异步操作。

#include <iostream>
#include <boost/asio.hpp>

#ifdef _WIN32
#include "Windows.h"
#endif

using namespace boost::asio::ip;
using namespace std;

int main(){
    int m_nPort = 12345;
    boost::asio::io_service io_service;
    tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), m_nPort));

    cout << "Waiting for connection..." << endl;

    tcp::socket socket(io_service);
    acceptor.accept(socket);
    cout << "connection accepted" << endl;
    try
    {
        socket.send(boost::asio::buffer("Start sending me data\r\n"));
    }
    catch(exception &e)
    {
        cerr << e.what() << endl; //"The parameter is incorrect" exception
    }
}

如何接收 10000 个字节并执行直到所有 10000 个字节到达或 1000 毫秒超时并抛出异常?


Boost 1.47.0 刚刚引入了超时功能basic_socket_iostream http://www.boost.org/doc/libs/release/doc/html/boost_asio/reference/basic_socket_iostream.html,即expires_at and expires_from_now方法。

这是一个基于您的代码片段的示例:

#include <iostream>
#include <boost/asio.hpp>

using namespace boost::asio::ip;
using namespace std;

int main(){
    int m_nPort = 12345;
    boost::asio::io_service io_service;
    tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), m_nPort));

    cout << "Waiting for connection..." << endl;

    tcp::iostream stream;
    acceptor.accept(*stream.rdbuf());
    cout << "Connection accepted" << endl;
    try
    {
        stream << "Start sending me data\r\n";

        // Set timeout in 5 seconds from now
        stream.expires_from_now(boost::posix_time::seconds(5));

        // Try to read 12 bytes before timeout
        char buffer[12];
        stream.read(buffer, 12);

        // Print buffer if fully received
        if (stream) // false if read timed out or other error
        {
            cout.write(buffer, 12);
            cout << endl;
        }
    }
    catch(exception &e)
    {
        cerr << e.what() << endl;
    }
}

这个程序在 Linux 上适合我。

请注意,我并不提倡您使用超时来代替带有截止时间计时器的异步操作。由您决定。我只是想证明超时是可能的basic_socket_iostream.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Boost ASIO套接字读取N个字节不多不少并等待它们到来或超时异常? 的相关文章

随机推荐