Boost asio socket write?



I'm attempting to learn boost asio. Starting off with the simple tests first.
This is a snippet of code that writes to a socket, but I keep getting the following exception thrown:
1
2
3
End point declared 
Socket Declared 
Error: system:111 connect: Connection refused

The code is a simple write, I have tried over a dozen different port numbers, none of which are in use, but the same error persists.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <boost/asio.hpp>
#include <iostream>
#include <string>

using namespace boost;

void write_to_socket(asio::ip::tcp::socket& sk, const std::string & msg ) {
  std::size_t total_write {0};  // bytes successfully witten
  std::size_t sz {msg.size()};
  
  // write_some returns the number of bytes sucessfully written
  while (total_write != sz ) {
    total_write += sk.write_some(asio::buffer(msg.c_str() + total_write, sz - total_write));
  }
  
}

void read_from_socket(asio::ip::tcp::socket& sk ) {
    /* to be coded */
}

int main() {
  std::string ip_addr {"127.0.0.1"};
  unsigned short port {5555};

  try {
    // initialise end point
    asio::ip::tcp::endpoint ep {asio::ip::address::from_string(ip_addr), port};
    
    std::cout << "End point declared \n";

    asio::io_service ios;

    // Configure socket with ios object and associated end point
    asio::ip::tcp::socket sk{ios, ep.protocol()};

    std::cout << "Socket Declared \n";
    sk.connect(ep); // connect socket to end point
    std::cout << "Socket Connected \n";

    write_to_socket(sk, "Hello World\n");
  }
  catch (system::system_error &e) {
    std::cout << "Error: " << e.code() << " " << e.what();
    return e.code().value();
  }
 
  return 0;
}


I can't see where the code is incorrect. Any suggestions anyone?

Connection refused means there is nothing listening on that port to accept connections. whatever server you're running on that port isn't actually running on that port.
thanks, so unless I code a server part, the client would always come back with such an exception for the given End point.
Topic archived. No new replies allowed.