linux - C++ boost/asio client doesn't connect to server -


i learning boost/asio ad wrote 2 programs(client , server) e-book minor changes. should connect server. when try connect outside world(some random http server ) , works when change destination "localhost:40002" says 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" , showed listening port server think works never less don't connect

server code:

#include <boost/asio.hpp> #include <iostream> #include <string> #include <ctime> std::string time_string() {    using namespace std;    time_t = 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));        (; ;) {          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 hint why connection doesn't happen

the second parameter ip::tcp::resolver::query service name, not port number:

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

should be

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

fyi, when compiled code on system failed:

resolve.cc: in function ‘int main()’: resolve.cc:7: error: invalid conversion ‘int’ ‘boost::asio::ip::resolver_query_base::flags’ resolve.cc:7: error:   initializing argument 2 of ‘boost::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]’ 

i'm surprised compiled you.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -