boost asio for sync server keeping TCP session open (with google proto buffers)

后端 未结 2 1038
甜味超标
甜味超标 2021-02-04 19:03

I currently have a very simple boost::asio server that sends a status update upon connecting (using google proto buffers):

try
{
  boost::asio::io_service io_ser         


        
相关标签:
2条回答
  • 2021-02-04 19:41

    In case anyone else wants to do this, here is the minimum to get above going: (similar to the tutorials, but a bit shorter and a bit different)

    class Session : public boost::enable_shared_from_this<Session>
    {
        tcp::socket socket;
        char buf[1000];
    public:
        Session(boost::asio::io_service& io_service)
            : socket(io_service) { }
        tcp::socket& SocketRef() { return socket; }
        void Read() {
            boost::asio::async_read( socket,boost::asio::buffer(buf),boost::asio::transfer_at_least(1),boost::bind(&Session::Handle_Read,shared_from_this(),boost::asio::placeholders::error));
        }
        void Handle_Read(const boost::system::error_code& error) {
            if (!error)
            {
                //read from buffer and handle requests
                //if you want to write sth, you can do it sync. here: e.g. boost::asio::write(socket, ..., ignored_error);
                Read();
            }
        }
    };
    
    typedef boost::shared_ptr<Session> SessionPtr;
    
    class Server
    {
        boost::asio::io_service io_service;
        tcp::acceptor acceptor;
    public:
        Server() : acceptor(io_service,tcp::endpoint(tcp::v4(), 13)) { }
        ~Server() { }
        void operator()() { StartAccept(); io_service.run(); }
        void StartAccept() {
            SessionPtr session_ptr(new Session(io_service));
            acceptor.async_accept(session_ptr->SocketRef(),boost::bind(&Server::HandleAccept,this,session_ptr,boost::asio::placeholders::error));
        }
        void HandleAccept(SessionPtr session,const boost::system::error_code& error) {
            if (!error)
              session->Read();
            StartAccept();
        }
    };
    

    From what I gathered through trial and error and reading: I kick it off in the operator()() so you can have it run in the background in an additional thread. You run one Server instance. To handle multiple clients, you need an extra class, I called this a session class. For asio to clean up dead sessions, you need a shared pointer as pointed out above. Otherwise the code should get you started.

    0 讨论(0)
  • 2021-02-04 20:04

    The examples you mention from the Boost.Asio documentation are actually pretty good to see how things work. You're right that at first it might look a bit difficult to understand, especially if you're new to these concepts. However, I would recommend that you start with the chat server example and get that built on your machine. This will allow you to closer look into things and start changing things in order to learn how it works. Let me guide you through a few things I find important to get started.

    From your description what you want to do, it seems that the chat server gives you a good starting point as it already has similar pieces you need. Having the server asynchronous is what you want as you then quite easily can handle multiple clients with a single thread. Nothing too complicated from the start.

    Simplified, asynchronous in this case means that your server works off a queue, taking a handler (task) and executes it. If there is nothing on the queue, it just waits for something to be put on the queue. In your case that means it could be a connect from a client, a new read of a message from a client or something like this. In order for this to work, each handler (the function handling the reaction to a particular event) needs to be set up.

    Let me explain a bit using code from the chat server example.

    In the server source file, you see the chat_server class which calls start_accept in the constructor. Here the accept handler gets set up.

    void start_accept()
    {
        chat_session_ptr new_session(new chat_session(io_service_, room_)); // 1
        acceptor_.async_accept(new_session->socket(),                       // 2
            boost::bind(&chat_server::handle_accept, this, new_session,     // 3
                boost::asio::placeholders::error));                         // 4
    }
    

    Line 1: A chat_session object is created which represents a session between one client and the server. A session is created for the accept (no client has connected yet).

    Line 2: An asynchronous accept for the socket...

    Line 3: ...bound to call chat_server::handle_accept when it happens. The session is passed along to be used by the first client which connects.

    Now, if we look at the handle_accept we see that upon client connect, start is called for the session (this just starts stuff between the server and this client). Lastly a new accept is put outstanding in case other clients want to connect as well.

    void handle_accept(chat_session_ptr session, 
                       const boost::system::error_code& error)
    {
        if (!error)
        {
            session->start();
        }
        start_accept();
    }
    

    This is what you want to have as well. An outstanding accept for incoming connections. And if multiple clients can connect, there should always be one of these outstanding so the server can handle the accept.

    How the server and the client(s) interact is all in the session and you could follow the same design and modify this to do what you want. You mention that the server needs to look at what is sent and do different things. Take a look at chat_session and the start function which was called by the server in handle_accept.

    void start()
    {
        room_.join(shared_from_this());
        boost::asio::async_read(socket_,
            boost::asio::buffer(read_msg_.data(), chat_message::header_length),
            boost::bind(
                &chat_session::handle_read_header, shared_from_this(),
                boost::asio::placeholders::error));
    }
    

    What is important here is the call to boost::asio::async_read. This is what you want too. This puts an outstanding read on the socket, so the server can read what the client sends. There is a handler (function) which is bound to this event chat_session::handle_read_header. This will be called whenever the server reads something on the socket. In this handler function you could start putting your specific code to determine what to do if a specific message is sent and so on.

    What is important to know is that whenever calling these asynchronous boost::asio functions things will not happen within that call (i.e. the socket is not read if you call the function read). This is the asynchronous aspect. You just kind of register a handler for something and your code is called back when this happens. Hence, when this read is called it will immediately return and you're back in the handle_accept for the server (if you follow how things get called). And if you remember there we also call start_accept to set up another asynchronous accept. At this point you have two outstanding handlers waiting for either another client to connect or the first client to send something. Depending on what happens first, that specific handler will be called.

    Also what is important to understand is that whenever something is run, it will run uninterrupted until everything it needs to do has been done. Other handlers have to wait even if there is are outstanding events which trigger them.

    Finally, in order to run the server you'll need the io_service which is a central concept in Asio.

    io_service.run();
    

    This is one line you see in the main function. This just says that the thread (only one in the example) should run the io_service, which is the queue where handlers get enqueued when there is work to be done. When nothing, the io_service just waits (blocking the main thread there of course).

    I hope this helps you get started with what you want to do. There is a lot of stuff you can do and things to learn. I find it a great piece of software! Good luck!

    0 讨论(0)
提交回复
热议问题