Cannot get boost::asio simple synchronous server tutorial program to work -- connection refused

StackOverflow https://stackoverflow.com/questions/23461173

  •  15-07-2023
  •  | 
  •  

Question

I am following the Introduction to Sockets boost::asio tutorial here, called a A synchronous TCP daytime client. I have copied the code exactly, but then moved them into Server.cpp and Client.cpp.

Server.cpp

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

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

std::string make_daytime_string()
{
  std::time_t now = time(0);
  return ctime(&now);
}

int main()
{
  try {
    std::cout << "Initiating server..." << std::endl;

    boost::asio::io_service io;

    tcp::acceptor acceptor (io, tcp::endpoint(tcp::v4(), 8889));

    for (;;) {
      tcp::socket socket (io);
      acceptor.accept(socket);

      std::string message = make_daytime_string();

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

  return 0;
}

Client.cpp

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

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

int main(int argc, char * argv[])
{
  boost::asio::io_service io;

  // Daytime
  try {
    if (argc != 2) {
      std::cerr << "Usage: client <host>" << std::endl;
      return 1;
    }

    tcp::resolver resolver (io);
    tcp::resolver::query query (argv[1], "daytime");
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

    tcp::socket socket (io);
    boost::asio::connect(socket, endpoint_iterator);

    for (;;) {
      boost::array<char, 128> buffer;
      boost::system::error_code error;
      size_t len = socket.read_some(boost::asio::buffer(buffer), error);

      if (error == boost::asio::error::eof) {
        break; // Connection closed cleanly by peer.
      }
      else if (error) {
        throw boost::system::system_error(error); // Some other error.
      }

      std::cout.write(buffer.data(), len);
    }
  }
  catch (std::exception & e) {
    std::cerr << e.what() << std::endl;
  }

  return 0;
}

First I run the server:

$ ./server 
Initiating server...

Then I run the client:

$ ./client localhost
connect: Connection refused

Since I am brand new to sockets and boost, unfortunately I am stuck on finding a solution to this connection refused error message.

Was it helpful?

Solution

Your server is running on port 8889.

Your client connects on port 13 (a.k.a. "daytime").

This will not work. For the obvious reason.

Note if you do decide to run the server on port 13, you need administrative privileges for that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top