本文介绍了升压ASIO套接字读取n个字节不多不少,或等待,直到他们超时异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建基于范例但还是做得不到如何创建,将读出的字节的一些量,如果将不会有足够将等待一个插座。我需要这是不是异步操作。

Creating a simple TCP server based on examples but still do not get how to create a socket that would read some amount of bytes and if there will not be enough would wait. I need this to be NOT asynchronous operation.

#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毫秒超时,并抛出一个异常?

How to receive 10000 bytes and do it either until all 10000 arrive OR 1000 millisecond timeout and throw an exception?

推荐答案

升压1.47.0刚刚推出了一个超时功能为<$c$c>basic_socket_iostream,即 expires_at expires_from_now 方法。

Boost 1.47.0 just introduced a timeout feature for basic_socket_iostream, namely, the expires_at and expires_from_now methods.

下面是根据你的代码片段的例子:

Here's an example based on your snippet:

#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上。

This program works for me on Linux.

请注意,我不主张你使用超时,而不是异步操作有最后期限计时器。这是由你来决定。我只是想表明,超时是可能的 basic_socket_iostream

Please note that I'm not advocating that you use timeouts instead of asynchronous operation with a deadline timer. It's up to you to decide. I just wanted to show that timeouts are possible with basic_socket_iostream.

这篇关于升压ASIO套接字读取n个字节不多不少,或等待,直到他们超时异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 11:01