zoukankan      html  css  js  c++  java
  • boost.asio防止恶意空连接的方法

    网络服务器通常要应对一些意外情况,如空连接行为,指在遇到客户端连接后不进行任何操作,并很可能在大量空连接情况下导致服务器资源耗尽而无法工作。

    以下代码主要工作在连接后首次接收客户端消息的环节添加一个timer,并在指定时间后检测是否已接收到消息(验证消息环节此处略去),如果没有收到消息则可认为这是一个非正常连接,并马上断开。timer使用boost::asio::deadline_timer,相对比较简单,详情如下:


    #include <boost/asio.hpp>
    #include <boost/bind.hpp>
    #include <boost/date_time/posix_time/posix_time_types.hpp>
    #include <boost/shared_ptr.hpp>
    #include <iostream>
    
    using namespace boost::asio;
    using boost::asio::ip::tcp;
    
    class Session : public boost::enable_shared_from_this<Session>
    {
    public:
        Session(boost::asio::io_service& io_service):
        timer_(io_service)
        ,socket_(io_service)
        ,is_read_(false)
        {
            Start();
        }
    
        void Start()
        {
            socket_.async_read_some
            (
                boost::asio::buffer(buff,1024),
                bind
                (
                    &Session::HandleRead,
                    shared_from_this(),
                    boost::asio::placeholders::error,
                    boost::asio::placeholders::bytes_transferred
                )
            );
            //当客户端连接上5秒钟以后检测是否进行了通信
            timer_.expires_from_now(boost::posix_time::seconds(5));
            timer_.async_wait(boost::bind(&Session::time_out, shared_from_this()));
        }
    
        void HandleRead(const boost::system::error_code& error, size_t len)
        {
            if (!error)
            {
                is_read_ = true;
                cout << buff << endl;
                socket_.async_read_some
                (
                    boost::asio::buffer(buff,1024),
                    bind
                    (
                        &Session::HandleRead,
                        shared_from_this(),
                        boost::asio::placeholders::error,
                        boost::asio::placeholders::bytes_transferred
                    )
                );
            }
        }
    private:
        void time_out()
        {
            //判断没有从客户端读取到消息的情况下断开连接
            if(!is_read_) socket_.close();
        }
    
    private:
        deadline_timer timer_;
        tcp::socket socket_;
        char buff[1024];
        bool is_read_;
    };
  • 相关阅读:
    Hibernate-----关系映射 重点!!!
    hibernate总结
    hibernate--session的CRUD方法, delete, load,get,update,saveorupdate, clear, flush
    hibernate--对象的三种状态Transient,Persistent,Detached
    hibernate--coreapi--configuration sessionfactory--getcurrentsession--opensession
    hibernate--联合主键--annotation
    Flutter Demo: 径向菜单动画
    Flutter Demo: PageView横向使用
    Flutter: 判断是Android还是Ios
    Flutter:发布包
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13318607.html
Copyright © 2011-2022 走看看