C ++ boost / asio client not connecting to server

I am studying boost / asio ad wrote 2 programs (client and server) from an e-book with minor changes. Basically, it should connect to my server. When I try to connect to the outside world (some random http server), everything is fine and it works, but when I change the destination to "localhost: 40002", it speaks of an invalid argument.

client code:

#include <boost/asio.hpp>
#include <iostream>

int main () {
   try {
      boost::asio::io_service io_service;
      boost::asio::ip::tcp::resolver::query query("localhost", 40002);
      boost::asio::ip::tcp::resolver resolver(io_service);
      boost::asio::ip::tcp::resolver::iterator destination = resolver.resolve(query);
      boost::asio::ip::tcp::resolver::iterator end ;
      boost::asio::ip::tcp::endpoint endpoint;

      while ( destination != end ) {
         endpoint = *destination++;
         std::cout<<endpoint<<std::endl;
      }

      boost::asio::ip::tcp::socket socket(io_service);
      socket.connect(endpoint);
   }
   catch (std::exception& e)
   {
      std::cerr << e.what() << std::endl;
   }
   return 0;
}

I did "netstat -l" and it showed that I really listen to my port, so the server I think is working on, but no less, it doesn’t connect

server code:

#include <boost/asio.hpp>
#include <iostream>
#include <string>
#include <ctime>
std::string time_string()
{
   using namespace std;
   time_t now = time(0);
   return ctime(&now);
}
int main () {

   try {
      boost::asio::io_service io_service;
      boost::asio::ip::tcp::acceptor acceptor(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 40002));

      for (; ;) {
         std::cout<<"Listening to"<<std::endl;
         boost::asio::ip::tcp::socket socket(io_service);
         acceptor.accept(socket);

         std::string message = time_string();
         boost::system::error_code ignored_error;
         boost::asio::write(socket, boost::asio::buffer(message), boost::asio::transfer_all(), ignored_error);
      }
   }
   catch (std::exception& e)
   {
      std::cerr << e.what() << std::endl;
   }
   return 0;

}

Can someone hint why the connection is not happening

+3
source share
1

ip::tcp::resolver::query - , :

  boost::asio::ip::tcp::resolver::query query("localhost", 40002);

  boost::asio::ip::tcp::resolver::query query("localhost", "40002");

fyi, , :

resolve.cc: In functionint main()’:
resolve.cc:7: error: invalid conversion frominttoboost::asio::ip::resolver_query_base::flagsresolve.cc:7: error:   initializing argument 2 ofboost::asio::ip::basic_resolver_query<InternetProtocol>::basic_resolver_query(const std::string&, boost::asio::ip::resolver_query_base::flags) [with InternetProtocol = boost::asio::ip::tcp]

, .

+5

Source: https://habr.com/ru/post/1756346/


All Articles