其他分享
首页 > 其他分享> > C Boost / Asio客户端未连接到服务器

C Boost / Asio客户端未连接到服务器

作者:互联网

我正在学习boost / asio广告从电子书编写了2个程序(客户端和服务器),并做了一些小的更改.
基本上它应该连接到我的服务器.
当我尝试连接到外部世界(某个随机的http服务器)时,一切都很好,并且可以正常工作,但是当我将目标更改为“ localhost:40002”时,它表示无效的参数.

客户代码:

#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;
}

我做了“ netstat -l”,它表明我确实在监听我的端口,因此我认为服务器可以工作,但至少它们不会连接

服务器代码:

#include <boost/asio.hpp>
#include <iostream>
#include <string>
#include <ctime>
std::string time_string()
{
   using namespace std;
   time_t now = 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));

      for (; ;) {
         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;

}

有人可以暗示为什么不发生连接

解决方法:

ip :: tcp :: resolver :: query的second parameter是服务名称,而不是端口号:

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

应该

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

仅供参考,当我在系统上编译您的代码时,它失败了:

resolve.cc: In function ‘int main()’:
resolve.cc:7: error: invalid conversion from ‘int’ to ‘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]’

我很惊讶它为您编译.

标签:networking,boost-asio,linux,c-4
来源: https://codeday.me/bug/20191023/1916707.html