C ++:BOOST-ASIO没有服务器导致客户端崩溃?

时间:2013-03-27 03:02:40

标签: c++ crash client boost-asio connector

以下代码在连接器boost::asio::connect(s, iterator);处崩溃并输出:

before connector:
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

Process returned 3 (0x3)   execution time : 1.281 s
Press any key to continue.

我没有连接localhost的端口4001上运行的服务器,我想知道是否有办法防止发生这种崩溃,以防服务器由于某种原因没有运行但客户端仍然可以运行软件有点。换句话说,有没有办法查看服务器是否存在而不会导致程序崩溃?

继承代码

//
// blocking_tcp_echo_client.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2012 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include <cstdlib>
#include <cstring>
#include <iostream>
#include <boost/asio.hpp>

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

enum { max_length = 1024 };

int main(int argc, char* argv[])
{
  //try
 // {
    //if (argc != 3)
    //{
    //  std::cerr << "Usage: blocking_tcp_echo_client <host> <port>\n";
    //  return 1;
    //}

    boost::asio::io_service io_service;

    tcp::resolver resolver(io_service);
    //tcp::resolver::query query(tcp::v4(), argv[1], argv[2]);
    tcp::resolver::query query(tcp::v4(), "127.0.0.1", "4001");
    tcp::resolver::iterator iterator = resolver.resolve(query);

    tcp::socket s(io_service);
    std::cout << "before connector: ";
    boost::asio::connect(s, iterator);
    std::cout << "after connector: ";
    using namespace std; // For strlen.
    std::cout << "Enter message: ";
    char request[max_length];
    std::cin.getline(request, max_length);
    size_t request_length = strlen(request);
    boost::asio::write(s, boost::asio::buffer(request, request_length));

    char reply[max_length];
    size_t reply_length = boost::asio::read(s,
        boost::asio::buffer(reply, request_length));
    std::cout << "Reply is: ";
    std::cout.write(reply, reply_length);
    std::cout << "\n";
  //}
  //catch (std::exception& e)
  //{
  //  std::cerr << "Exception: " << e.what() << "\n";
  //}

  return 0;
}

1 个答案:

答案 0 :(得分:3)

boost::asio::connect引发错误。因此,try {}块和注释掉的catch {}块对于检测错误而不是崩溃非常有用。

如果找不到端口,

resolver.resolve(query)返回.end()而不是有效的迭代器,因此您可以在尝试调用connect之前先测试迭代器

来自提升文档:

  • @throws boost :: system :: system_error失败时抛出。如果顺序是
  • 为空,关联的@c error_code为boost :: asio :: error :: not_found。
  • 否则,包含上次连接尝试的错误。