Unable to get boost :: asio simple program for a synchronous server to work - connection refused

I follow the instructions in the Introduction to Sockets boost::asio here , which is called the TCP Synchronous Day Client. I copied the code exactly, but then moved them to 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 start the server:

$ ./server 
Initiating server...

Then I started the client:

$ ./client localhost
connect: Connection refused

Since I am new to sockets and upgrading, unfortunately, I am stuck looking for a solution to this failed error message.

+4
source share
1 answer

The server runs on port 8889.

Your client connects to port 13 (aka "daytime").

This will not work. For obvious reason.

, 13, .

+3

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


All Articles