C
C
cunion2020-12-21 01:12:41
C++ / C#
cunion, 2020-12-21 01:12:41

Why is the echo server not working on boost::asio?

Hello! Recently started learning boost::asio. Some time later I decided to write an echo server. I was able to do this, but I realized that a maximum of one client can connect to the server at the same time. Deciding to remove this drawback, I ran into a problem: when trying to connect two clients, one can send and receive a response from the server, while the second cannot. Here is the code:

#include <boost/asio.hpp>
#include <iostream>
using namespace boost::asio;

void read_and_echo(ip::tcp::socket& sock)
{
  char buff[512];
  
  while (true)
  {
    sock.wait(ip::tcp::socket::wait_read);
    sock.read_some(buffer(buff));
    sock.write_some(buffer(buff));
  }
}

int main()
{
  io_service io;
  ip::tcp::endpoint ep(ip::tcp::v4(), 80);
  ip::tcp::acceptor ac(io, ep);
  std::vector<ip::tcp::socket> sockets;
  boost::thread_group th;

  while (true)
  {
    sockets.push_back(ac.accept());
    std::cout << "Accept client" << std::endl;
    th.create_thread([&sockets]()
      {
        read_and_echo(sockets.back());
      });
  }

  th.join_all();
  return 0;
}


After connecting the second client, the server displays "Accept Client" for the second time, after which an error occurs. Please tell me what is the error, it seems to me that two clients are connected on the same port, but perhaps the problem is in another.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
X
xorknown, 2020-12-21
@0hquazEd

Problem in a choice of the container for sockets. The vector has a feature, it distributes all its elements sequentially in memory and allocates memory for them in advance. At some point, when adding an element , for example, it can change the location of this sequential section in memory. And it turns out that in your threads you refer to the memory in which the sockets are no longer located. std::vector::reserve is just a temporary deferral of a problem that will show up with more connections.
You should consider replacing the vector with a std::list , for example, which does not have this feature.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question