在boost async_receive_from上定义超时

时间:2017-12-13 09:32:54

标签: c++ sockets boost boost-asio

我有一个boost套接字,我定义了一个异步接收:

Keywords_33=[('File_2', ['with', 'as']),
         ('Module_2', ['from', 'import']),
         ('Constant_3', {'bool': ['False', 'True'],
                         'none': ['None']}),
         ('Operator_4', {'boolean_operation': {'or', 'and', 'not'},
                         'comparison': {'is'}}),
         ('Container_operation_2', ['in', 'del']),
         ('Klass_1', ['class']),
         ('Function_7',['lambda', 'def', 'pass',
                        'global', 'nonlocal',
                        'return', 'yield']),
         ('Repetition_4', ['while', 'for', 'continue', 'break']),
         ('Condition_3', ['if', 'elif', 'else']),
         ('Debug_2', ['assert', 'raise']),
         ('Exception_3', ['try', 'except', 'finally'])]

kwlist = ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def',
      'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import',
      'in','is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while',
      'with', 'yield']

if __name__ == '__main__':
    result = []
    for kw in kwlist:
        for key in Keywords_33:
            if isinstance(key[1], list):
                for i in key[1]:
                    if kw == i:
                        result.append(i)
            elif isinstance(key[1], dict):
                for value in key[1].values():
                    for j in value:
                        if kw == j:
                            result.append(j)

    print(result)

但是如果没有事件进入这个套接字(套接字上没有数据包),我会陷入lambda方法......

有没有办法在这个rec​​v上定义超时?

1 个答案:

答案 0 :(得分:0)

  

有没有办法在这个rec​​v上定义超时?

如果对Component::recv的调用本身是asio - 操作,您可以定义一个截止时间计时器,在超时时取消读取操作。您可以在Boost documentation中找到示例(示例/ cpp03 / timeouts / blocking_tcp_client.cpp)。

否则,您可以使用std :: future:

using namespace std::chrono_literals;
auto fut = std::async(std::launch::async, &Component::recv, handler);
if(fut.wait_for(500ms) == std::future_status::timeout) {
   // timed out
}