Simple server/client boost example not working

Milan picture Milan · Apr 4, 2009 · Viewed 11.6k times · Source

Learning boost, and compiled their daytime server client example. Since I cant use port 13 that is in the example I only changed the port numbers in the server and client example. Server runs fine, but the client doesnt connect it seems, and no error is given.

Input data for the client is "127.0.0.1".

Server:

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

using boost::asio::ip::tcp;

std::string make_daytime_string()
{
  using namespace std; // For time_t, time and ctime;
  time_t now = time(0);
  return ctime(&now);
}

int main()
{
  try
  {
    boost::asio::io_service io_service;

    tcp::endpoint endpoint(tcp::v4(), 8087);
    tcp::acceptor acceptor(io_service, endpoint);

    for (;;)
    {
      tcp::iostream stream;
      acceptor.accept(*stream.rdbuf());
      stream << "test" << make_daytime_string();
    }
  }
  catch (std::exception& e)
  {
    std::cerr << e.what() << std::endl;
  }

  return 0;
}

And the client:

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

using boost::asio::ip::tcp;

int main(int argc, char* argv[])
{
  try
  {
    if (argc != 2)
    {
      std::cerr << "Usage: daytime_client <host>" << std::endl;
      return 1;
    }

    tcp::iostream s(argv[1], 8087);
    std::string line;
    std::getline(s, line);
    std::cout << line << std::endl;
  }
  catch (std::exception& e)
  {
    std::cout << "Exception: " << e.what() << std::endl;
  }

  return 0;
}

Answer

Bleyddyn picture Bleyddyn · Jun 18, 2011

What worked for me was to change the way I create the endpoint from

tcp::endpoint( tcp::v4(), port );

to

tcp::endpoint( boost::asio::ip::address::from_string("127.0.0.1"), port );

The first method creates an endpoint of 0.0.0.0 which works fine on Mac OS X, but gives the "not valid" message on Windows (XP, building with MSVC 2008).

I wouldn't mind knowing WHY the difference, but at least it works.