2

Guys I really need your help. I'm learning boost::asio and I have 2 problems that I can't deal for days...

Here is an example of a simple echo server done by myself:

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));
}

The problem is the server accept one client and it does not accept other pending client.. where am i doing wrong here

NOTE: I wrote this code in notepad so sorry for syntax errors if there are any.

Thanks for your help in advance!!!

Dmitry
  • 6,716
  • 14
  • 37
  • 39
  • async_accept will accept one connection. You need to call it again in your `accept_handle` function. – Richard Hodges Sep 29 '17 at 13:15
  • 1
    Possible duplicate of [How do I create a boost Server that can handle multiple clients at once?](https://stackoverflow.com/questions/31579362/how-do-i-create-a-boost-server-that-can-handle-multiple-clients-at-once) – Euri Pinhollow Sep 29 '17 at 13:20
  • Richard Hodges you mean i need to call my accept_handle to accept another connection at the time the server is reading from a client but why is it wrong to call async_handle from write_handle??? – Abror Umaraliyev Sep 29 '17 at 14:39
  • For reference https://stackoverflow.com/questions/46435719/boost-asio-simple-echo-server-without-class/46436274#46436274 – sehe Sep 30 '17 at 02:12

1 Answers1

1

The code can only accept one connection because it is not calling async_accept in the accept_handle function.

The code may also have a problem with object lifetimes: it would be wise to use shared pointers to manage the clients see: Boost async_* functions and shared_ptr's.

Andriy Tylychko
  • 15,967
  • 6
  • 64
  • 112
kenba
  • 4,303
  • 1
  • 23
  • 40
  • @Gruffalo, thank you for editing my answer to change `write_accept` to `async_accept`. However, @Abor's code has a function called `write_accept` that creates a `newConnection` and then calls `async_accept`... – kenba Oct 02 '17 at 08:59