Home > OS >  asio tcp server hanging
asio tcp server hanging

Time:12-05

I know this is probably a really simple problem but ive been trying to get the asio examples to work correctly for over a week now. whenever I run the program, the terminal hangs and dosent print anything and dosent send any info to the client. Im using Ubuntu Linux and a basic compiler command

g   main.cpp -o main.exe -I include
#define ASIO_STANDALONE;
#include <ctime>
#include <iostream>
#include <string>
#include <asio.hpp>

using asio::ip::tcp;


int main()
{
  try
  {
    asio::io_context io_context;

    tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), 1326));

    for (;;)
    {
      std::cout << "hi";
      tcp::socket socket(io_context);
      acceptor.accept(socket);

      std::string message = "e";

      asio::error_code ignored_error;
      asio::write(socket, asio::buffer(message), ignored_error);
      break;
    }
  }
  catch (std::exception& e)
  {
    std::cerr << e.what() << std::endl;
  }

  return 0;
}

any help would be much appreciated

CodePudding user response:

the terminal hangs and dosent print anything and dosent send any info to the client

You need to connect a client first, because the first thing you do is a blocking accept which never completes unless a connection arrives.

I've compiled your program (with minor modification for Boost Asio):

enter image description here

  • Related