1. 程式人生 > >boost::asio伺服器處理多個客戶端連線(服務端程式)

boost::asio伺服器處理多個客戶端連線(服務端程式)

class talk_to_client //: boost::enable_shared_from_this<talk_to_client>

{

public:

    talk_to_client():m_sock(service),already_read(0){}

    string username(){return this->user;}

    ip::tcp::socket &sock(){return this->m_sock;}

    bool read_complete(boost::system::error_code &erro,size_t bytes)

    {

        if(erro)return 0;

        already_read=bytes;

        bool found=find(buff,buff+bytes,'*')<buff+bytes;

        return found?0:1;

    }

    void answer_to_client()

    {

        try{

            read_request();

            process_msg();

           }

        catch(boost::system::system_error &)

        {

            stop();

        }

    }

    void read_request()

    {

        already_read+=m_sock.read_some(buffer(buff));

        

    }

    void process_msg()

    {

        bool found_enter=find(buff,buff+already_read,'*')<buff+already_read;

        if(!found_enter)return;

        size_t pos=find(buff,buff+already_read,'*')-buff;

        

            string msg(buff,pos);

            cout<<msg<<endl;

            if(msg=="to do something*")

            {

                write(" got it");

            }

        

    }

    void stop()

    {

        m_sock.close();

    }

    void write(string msg)

    {

        m_sock.write_some(buffer(msg));

    }

private:

    ip::tcp::socket m_sock;

    size_t already_read;

    string user;

    char buff[1024];

};

 

//boost::shared_ptr<talk_to_client> ptr;

vector<boost::shared_ptr<talk_to_client>> clients;

boost::recursive_mutex cs;

void accept_thread()

{

    io_context context;

    ip::tcp::acceptor a(context,ip::tcp::endpoint(ip::tcp::v4(),8080));

    while(true)

    {

        boost::shared_ptr<talk_to_client> new_(new talk_to_client);

        a.accept(new_->sock());

        boost::recursive_mutex::scoped_lock lk(cs);

        clients.push_back(new_);

    }

}

void handle_msg_thread()

{

    while(true)

    {

        boost::this_thread::sleep(boost::posix_time::millisec(100));

        for(vector<boost::shared_ptr<talk_to_client>>::iterator b=clients.begin(),e=clients.end();e!=b;b++)

        {

            (*b)->answer_to_client();

        }

    }

}

 

int main()

{

    boost::thread_group threads;

    threads.create_thread(accept_thread);

    threads.create_thread(handle_msg_thread);

    threads.join_all();

    return 0;

}