2017-09-29 56 views
2

夥計們我真的需要你的幫助。我正在學習boost::asio和我有2個問題,我不能處理好幾天......boost :: asio服務器功能簡單

下面是我自己做了一個簡單的echo服務器的例子:

int main(
{ 
    // crate a server, binding it and listening connections 

    // acceptor server; 

    //socket client 

    server.async_accept(client, boost::bind(accept_handle, _1, &server, &client)); 

    io_service.run(); 

    return 0; 
} 

void accept_handle(const boost::system::error_code& eCode, boost::asio::ip::tcp::acceptor* server, boost::asio::ip::tcp::socket* client) 
{ 
    char data[43]; 
    client->async_read_some(boost::asio::buffer(data, 20), boost::bind(read_handle, _1, _2, server, client)); 
} 

void read_handle(const boost::system::error_code& eCode, size_t bytes) 
{ 
    char data_buf[20] = "hello"; 
    client->async_write_some(boost::buufer(data, 5), boost::bind(write_handle, _1, _2, server, client)); 
} 

void write_accept(const boost::system::error_code& eCode, size_t bytes) 
{ 
    boost::asio::ip::tcp::socket newConnection(server->get_ioservice)); // taking he io_service of the server 

    server->async_accept(newConnection, boost::bind(accept_handle, _1, server, client)); 
} 

的問題是服務器接受一個客戶端,它不接受其它待處理的客戶..我在哪裏錯了在這裏做

注意:我在記事本中的語法錯誤很抱歉寫了這個代碼,如果有任何。

感謝您的幫助!

+0

async_accept將接受一個連接。您需要在'accept_handle'函數中再次調用它。 –

+1

可能的重複[如何創建一個可以同時處理多個客戶端的boost服務器?](https://stackoverflow.com/questions/31579362/how-do-i-create-a-boost-server-that- can-handle-multiple-clients-at-once) –

+0

Richard Hodges你的意思是我需要調用我的accept_handle在服務器讀取客戶端時接受另一個連接,但爲什麼從write_handle中調用async_handle會出錯? –

回答

0

該代碼只能接受一個連接,因爲它是而不是accept_handle函數中調用async_accept

代碼也可能在對象生命週期中存在問題:使用共享指針來管理clients請參閱:Boost async_* functions and shared_ptr's

+0

@Gruffalo,感謝您編輯我的答案,將'write_accept'改爲'async_accept '。不過,@ Abor的代碼有一個名爲'write_accept'的函數,它創建一個'newConnection',然後調用'async_accept' ... – kenba

+0

oops,對不起:) ... –