2016-04-17 27 views
0

我目前正在創建使用boost ::短耳,做兩個簡單的服務器應用程序:的boost ::短耳 - async_wait在async_accept處理程序崩潰的應用程序

  1. 接受客戶端的傳入連接
  2. 一旦客戶端已被接受,開始boost::asio::deadline_timer其重演

下面的代碼顯示了我當前的嘗試:

#define BOOST_ASIO_ENABLE_HANDLER_TRACKING 

#include <WinSock2.h> 
#include <Mswsock.h> 
#include <boost/asio/io_service.hpp> 
#include <boost/asio/ip/tcp.hpp> 
#include <boost/bind.hpp> 
#include <boost/date_time/posix_time/posix_time.hpp> 

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

void timerHandler(const boost::system::error_code& errorCode, deadline_timer* timer) { 
    timer->expires_at(timer->expires_at() + boost::posix_time::seconds(1)); 
    timer->async_wait(boost::bind(timerHandler, _1, timer)); 
} 

void acceptHandler(const boost::system::error_code &errorCode, io_service *ioService) { 
    deadline_timer timer(*ioService, boost::posix_time::seconds(1)); 
    timer.async_wait(boost::bind(timerHandler, _1, &timer)); 
} 

int main(int argc, char** argv) { 
    io_service ioService; 
    tcp::socket socket(ioService); 
    tcp::acceptor acceptor{ ioService, tcp::endpoint{ tcp::v4(), 12345 } }; 
    acceptor.listen(); 
    acceptor.async_accept(socket, boost::bind(acceptHandler, _1, &ioService)); 
    ioService.run(); 
    return EXIT_SUCCESS; 
} 

問題

計時器不知何故預期在acceptHandler不起作用。不知何故,它被取消兩次,觸發一個錯誤,並最終崩潰整個應用程序。

處理器跟蹤輸出

@asio|1460922050.075890|0*1|[email protected]_accept 
@asio|1460922051.153952|>1|ec=system:0 
@asio|1460922051.153952|1*2|[email protected]_wait 
@asio|1460922051.153952|1|[email protected] 
@asio|1460922051.153952|<1| 
@asio|1460922051.153952|>2|ec=system:995 
@asio|1460922051.153952|2|[email protected] 

問題

  1. 是什麼原因導致acceptHandler取消deadline_timer在處理程序跟蹤輸出的4線?
  2. 處理程序跟蹤輸出第6行中的錯誤995是什麼結果?錯誤信息是:由於線程退出或應用程序請求

  3. 是什麼原因導致的timerHandler取消在處理程序跟蹤輸出的第7行的deadline_timer的的I/O操作已中止?

回答

2

timeracceptHandler在棧上分配的,因此不是由時間timerHandler被稱爲有效。您需要動態分配計時器。

此外,你應該檢查兩個處理程序中的錯誤代碼。當你想結束程序和計時器時,這一點尤其重要。

+1

多麼愚蠢的錯誤。謝謝。我在這裏留下了簡單的錯誤檢查。我通常在所有處理程序中使用switch-case。 – chrisp