BOOST ASIO - How to write console server

前端 未结 2 434
臣服心动
臣服心动 2020-12-01 20:21

I have to write asynchronous TCP Sever. TCP Server have to be managed by console (for eg: remove client, show list of all connected client, etcc..)

The problem is: H

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 21:00

    The problem is: How can I attach (or write) console, which can calls above functionalities. This console have to be a client? Should I run this console client as a sepearate thread?

    You don't need a separate thread, use a posix::stream_descriptor and assign STDIN_FILENO to it. Use async_read and handle the requests in the read handlers.

    #include 
    
    #include 
    #include 
    #include 
    
    #include 
    
    using namespace boost::asio;
    
    class Input : public boost::enable_shared_from_this
    {
    public:
        typedef boost::shared_ptr Ptr;
    
    public:
        static void create(
                io_service& io_service
                )
        {
            Ptr input(
                    new Input( io_service )
                    );
            input->read();
        }
    
    private:
        explicit Input(
                io_service& io_service
             ) :
            _input( io_service )
        {
            _input.assign( STDIN_FILENO );
        }
    
        void read()
        {
            async_read(
                    _input,
                    boost::asio::buffer( &_command, sizeof(_command) ),
                    boost::bind(
                        &Input::read_handler,
                        shared_from_this(),
                        placeholders::error,
                        placeholders::bytes_transferred
                        )
                    );
        }
    
        void read_handler(
                const boost::system::error_code& error,
                size_t bytes_transferred
                )
        {
            if ( error ) {
                std::cerr << "read error: " << boost::system::system_error(error).what() << std::endl;
                return;
            }
    
            if ( _command != '\n' ) {
                std::cout << "command: " << _command << std::endl;
            }
    
            this->read();
        }
    
    private:
        posix::stream_descriptor _input;
        char _command;
    };
    
    int
    main()
    {
        io_service io_service;
        Input::create( io_service );
        io_service.run();
    }
    

提交回复
热议问题