2013-10-02 22 views
0

我非常喜欢boost :: asio,所以请帮助我。boost :: asio如何从客户端异步读取数据并定期写入数据(如果有的话)

我需要编写单线程TCP服务器。服务器应该接受客户端连接并不断从客户端套接字读取输入数据。定期服务器应该向客户端发送数据。所以我有一些这样的问题 - 所有的例子说明情况时,我们总是有循环

  1. async_receive()
  2. on_receive() - > ASYNC_WRITE()
  3. on_write() - >转到1 :)

所以我的决定是使用计时器来检查要发送到套接字的数据。

我写了测试服务器,并有非常奇怪的行为 - 如果客户端连接,做一些事情,并与一些时间三角洲一个接一个断开连接工作正常。但是,如果所有的客户端同时断开连接,我有 情况定时器处理程序尝试使用DESTROYED对象(锁定关键部分)的成员类。

我无法形容为什么!请帮忙 !

[这部影片展示它是如何转载](http://www.youtube.com/watch?v=NMWkD7rqf7Y&feature=youtu.be “1080”)

谢谢!

#include <boost/none.hpp> 
#include <boost/bind.hpp> 
#include <boost/asio.hpp> 
#include <boost/shared_ptr.hpp> 
#include <boost/enable_shared_from_this.hpp> 

#include <iostream> 




using namespace boost::asio; 
using namespace boost::posix_time; 



class CIncommingConnection ; 
typedef boost::shared_ptr<CIncommingConnection> CIncommingConnectionPtr; 


struct IIncomingServer 
{ 
    virtual void OnData(CIncommingConnectionPtr pConn, const char *pData, size_t bytes) = 0; 
    virtual void OnConnected(CIncommingConnectionPtr pConn) = 0; 
    virtual void OnDisconnected(const boost::system::error_code& err, CIncommingConnectionPtr pConn) = 0; 
}; 



class CAutoLock 
{ 
public: 
    CAutoLock(CRITICAL_SECTION &cs) : 
     m_cs(cs) 
    { 
     ::EnterCriticalSection(&m_cs); 
    } 

    ~CAutoLock() 
    { 
     ::LeaveCriticalSection(&m_cs); 
    } 

private: 
    CRITICAL_SECTION &m_cs; 
}; 

class CIncommingConnection : public boost::enable_shared_from_this<CIncommingConnection>      
          ,boost::noncopyable 
{ 
public: 

    CIncommingConnection(const std::string sPeerName, boost::asio::io_service &service, IIncomingServer *pServer) : 
    m_service(service) 
    ,sock_(service) 
    ,m_sPeerName(sPeerName) 
    ,m_pServer(pServer) 
    ,m_timer(service) 
    { 
     ::InitializeCriticalSection(&m_cs); 

     std::cout << "CIncommingConnection()" << std::endl ; 
    } 


    ~CIncommingConnection() 
    { 
     std::cout << "CIncommingConnection()~" << std::endl ; 
     ::DeleteCriticalSection(&m_cs); 
    } 


    ip::tcp::socket & sock() 
    { 
     return sock_; 
    } 



    void start() 
    { 
     m_pServer->OnConnected(shared_from_this()); 
     do_read(); 
     wait_for_outgoingdata(); 
    } 


private: 

    void stop() 
    {  
     sock_.close(); 
     m_timer.cancel(); 
    } 



    void do_read() 
    { 
     sock_.async_receive(buffer(read_buffer_), boost::bind(&CIncommingConnection::handler_read, this, _1, _2)); 
    } 



    void do_error(const boost::system::error_code& error) 
    { 
     CIncommingConnectionPtr pConn = shared_from_this(); 

     stop() ; 

     m_pServer->OnDisconnected(error, pConn); 
    } 



    void handler_read(const boost::system::error_code& error, std::size_t bytes) 
    { 
     if (error) 
     { 
      do_error(error); 
      return ; 
     } 

     CIncommingConnectionPtr pConn = shared_from_this() ; 

     m_pServer->OnData(pConn, read_buffer_, bytes); 

     do_read(); 
    } 



    void wait_for_outgoingdata() 
    { 
     m_timer.expires_from_now(boost::posix_time::millisec(100)); 
     m_timer.async_wait(boost::bind(&CIncommingConnection::on_output_queue_timer, this, _1)); 
    } 



    void on_output_queue_timer(const boost::system::error_code& error) 
    { 
     if (error == boost::asio::error::operation_aborted) 
     { 
      return ; 
     } 

     CAutoLock oLock(m_cs); 

     if (!m_sOutBuf.empty()) 
      sock_.async_send(buffer(m_sOutBuf), boost::bind(&CIncommingConnection::handler_write, this, _1, _2)); 
     else 
      wait_for_outgoingdata(); 
    } 


    void handler_write(const boost::system::error_code& error, std::size_t bytes) 
    {  
     if (error) 
      return ; 


     if (bytes) 
     { 
      m_sOutBuf = m_sOutBuf.substr(bytes, m_sOutBuf.length()-bytes); 
     } 

     wait_for_outgoingdata(); 
    } 



private: 
    ip::tcp::socket sock_; 

    enum { max_msg = 1024 }; 
    char read_buffer_[max_msg]; 
    char write_buffer_[max_msg]; 


    boost::asio::io_service  &m_service ; 
    std::string      m_sPeerName ; 
    std::string      m_sOutBuf; 
    CRITICAL_SECTION    m_cs ; 
    IIncomingServer    *m_pServer; 
    boost::asio::deadline_timer  m_timer; 
}; 






class CIncomingServer : public boost::enable_shared_from_this<CIncomingServer>      
         , public IIncomingServer 
         , boost::noncopyable 
{ 

public: 

    CIncomingServer(boost::asio::io_service &service, 
     unsigned int port, 
     bool bAllowManyConnections, 
     const std::string sPeerName) : 

     m_acceptor (service, ip::tcp::endpoint(ip::tcp::v4(), port), false) 
    ,m_sPeerName(sPeerName) 
    ,m_port(port) 
    ,m_service(service) 
    ,m_timer(service) 
    ,m_bAllowManyConnections(bAllowManyConnections) 
    { 
    } 



    ~CIncomingServer() 
    { 
    } 



    void run() 
    { 
     CIncommingConnectionPtr pConn (new CIncommingConnection(m_sPeerName, m_service, this)); 
     m_clients.push_back(pConn); 


     m_acceptor.async_accept(pConn->sock(), boost::bind(&CIncomingServer::handle_accept, this, _1)); 

     m_timer.expires_from_now(boost::posix_time::millisec(500)); 
     m_timer.async_wait(boost::bind(&CIncomingServer::on_timer, this)); 
    } 




private: 

    void handle_accept(const boost::system::error_code & err) 
    { 
     m_clients.back()->start(); 

     CIncommingConnectionPtr pConnNew (new CIncommingConnection(m_sPeerName, m_service, this)); 
     m_clients.push_back(pConnNew); 

     m_acceptor.async_accept(pConnNew->sock(), boost::bind(&CIncomingServer::handle_accept, this, _1)); 
    } 


    //IIncomingServer 
    virtual void OnData(CIncommingConnectionPtr pConn, const char *pData, size_t bytes) 
    { 
     std::cout << "Data received" << std::endl ; 
    } 


    virtual void OnConnected(CIncommingConnectionPtr pConn) 
    { 
     std::cout << "Client connected" << std::endl ; 
    } 


    virtual void OnDisconnected(const boost::system::error_code& err, CIncommingConnectionPtr pConn) 
    { 
     std::cout << "Client disconnected" << std::endl ; 

     auto it = std::find(m_clients.begin(), m_clients.end(), pConn) ; 
     if (it != m_clients.end()) 
     { 
      m_clients.erase(it); 
     } 

    } 



    void on_timer() 
    { 
     //if (NeedTerminate()) 
     //{ 
     // m_service.stop(); 
     // return ; 
     //} 

     m_timer.expires_from_now(boost::posix_time::millisec(500)); 
     m_timer.async_wait(boost::bind(&CIncomingServer::on_timer, this)); 
    } 



private: 
    ip::tcp::acceptor m_acceptor ; 

    std::vector<CIncommingConnectionPtr> m_clients; 
    std::string m_sPeerName ; 
    unsigned int m_port ; 
    boost::asio::io_service  &m_service ; 
    boost::asio::deadline_timer m_timer; 
    bool       m_bAllowManyConnections; 
}; 


int _tmain(int argc, _TCHAR* argv[]) 
{ 

    boost::asio::io_service service ; 


    boost::shared_ptr<CIncomingServer> pServer; 

    try 
    { 
     pServer.reset(new CIncomingServer(service, 8000, false, "BS Server"));   
     pServer->run(); 
    } 
    catch (const boost::system::system_error &err) 
    { 
     std::cout << "Error : " << err.what() << std::endl ; 
     return 0 ; 
    } 

    service.run(); 

    return 0 ; 


} 
+0

+1视频:) –

+1

-1。这是[SSCCE](http://sscce.org/)吗?我对此表示怀疑。 – Abyx

+1

对不起,艾比 - 但我不同意你的疑惑。例如,在这个示例中,你认为什么样的细节不重要?但谢谢你的批评! – user1503944

回答

2

长话短说:你应该绑定完成处理程序,以一个shared_ptr从shared_from_this()返回,而不是普通的this(所谓shared_from_this成语)。这样您可以确保连接对象使用寿命的正确自动管理。

从技术上讲,以下现在会发生:do_error导致2个动作来发生:

  1. 定时器取消(这是异步操作)从容器移除的
  2. CIncommingConnectionPtr(这是同步 操作)。

在点(2)连接被破坏,因为没有其他shared_ptr s持有它。现在timer completion handler comes ...崩溃!

+0

谢谢你的回答! 看起来这是正确的,但我无法从中得出正确的结论:-( )在将shared_from_this()传递给异步处理程序之后,我的程序不再崩溃,但并非所有CIncommingConnection实例都被销毁 这看起来像我想念一些参考,而对象仍然活着 今天我将尝试调查这种情况!非常感谢! – user1503944

+0

@ user1503944好,一目了然,我没有看到任何“永恒”上面代码中的'shared_ptr'(即使绑定到'shared_from_this'后)。也许,你的真实代码与你发布的不一样。 (顺便说一下,我建议你避免在缓冲区上显式锁定 - 相反,你可以将任何与缓冲区相关的代码发布到io_service上。) –

+2

@ user1503944:简要介绍一下代码, 'CIncommingConnection :: on_output_queue_timer()'调用链可能会维护引用。即使'timer.cancel()'被调用,调用链可能会继续。有关此行为的详细信息,请参阅[文档](http://www.boost.org/doc/libs/1_54_0/doc/html/boost_asio/reference/basic_deadline_timer/cancel/overload1.html#boost_asio.reference.basic_deadline_timer。 cancel.overload1.remarks)备注。为了解决这个问题,考虑错误时返回'on_output_queue_timer()'或者'sock_.is_open()'为false。 –

相关问题