升压套接字通信在一次交换后无法正常工作

boost socket comms are not working past one exchange

我正在转换一个应用程序,该应用程序在两个服务之间具有非常简单的心跳/状态监控连接。由于除了 windows 之外,现在还需要在 linux 上对 运行 进行修改,我想我会使用 boost(v1.51,但我无法升级 - linux编译器太旧并且 windows 编译器是 visual studio 2005)来完成使其与平台无关的任务(考虑到,我真的不希望有两个代码文件,每个代码文件一个 OS,或者整个代码中乱七八糟的#defines,当 boost 提供阅读愉快的可能性时(我签入后 6 个月忘记了这段代码!)

我现在的问题是连接超时。实际上,它根本没有用。

第一次发送 'status' 消息,它被服务器端接收并发回适当的响应。服务器端然后返回到套接字等待另一条消息。客户端(此代码)再次发送 'status' 消息......但是这次,服务器从未收到它并且 read_some() 调用阻塞,直到套接字超时。我觉得

真的很奇怪

服务器端没有改变。唯一改变的是我将客户端代码从基本的 winsock2 套接字更改为此代码。以前,它连接并循环发送/接收调用,直到程序中止或收到 'lockdown' 消息。

为什么后续调用(发送)静默地无法在套接字上发送任何内容,我需要调整什么才能恢复简单的发送/接收流程?

#include <boost/signals2/signal.hpp>
#include <boost/bind.hpp>
#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/thread.hpp>

using boost::asio::ip::tcp;
using namespace std;

boost::system::error_code ServiceMonitorThread::ConnectToPeer(
    tcp::socket &socket,
    tcp::resolver::iterator endpoint_iterator)
{
    boost::system::error_code error;
    int tries = 0;

    for (; tries < maxTriesBeforeAbort; tries++)
    {
        boost::asio::connect(socket, endpoint_iterator, error);

        if (!error)
        {
            break;
        }
        else if (error != make_error_code(boost::system::errc::success))
        {
            // Error connecting to service... may not be running?
            cerr << error.message() << endl;
            boost::this_thread::sleep_for(boost::chrono::milliseconds(200));
        }
    }

    if (tries == maxTriesBeforeAbort)
    {
        error = make_error_code(boost::system::errc::host_unreachable);
    }

    return error;
}

// Main thread-loop routine.
void ServiceMonitorThread::run() 
{
    boost::system::error_code error;

    tcp::resolver resolver(io_service);
    tcp::resolver::query query(hostnameOrAddress, to_string(port));
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

    tcp::socket socket(io_service);

    error = ConnectToPeer(socket, endpoint_iterator);
    if (error && error == boost::system::errc::host_unreachable)
    {
        TerminateProgram();
    }

    boost::asio::streambuf command;
    std::ostream command_stream(&command);
    command_stream << "status\n";

    boost::array<char, 10> response;
    int retry = 0;

    while (retry < maxTriesBeforeAbort)
    {
        // A 1s request interval is more than sufficient for status checking.
        boost::this_thread::sleep_for(boost::chrono::seconds(1));

        // Send the command to the network monitor server service.
        boost::asio::write(socket, command, error);

        if (error)
        {
            // Error sending to socket
            cerr << error.message() << endl;
            retry++;
            continue;
        }

        // Clear the response buffer, then read the network monitor status.
        response.assign(0);
        /* size_t bytes_read = */ socket.read_some(boost::asio::buffer(response), error);

        if (error)
        {
            if (error == make_error_code(boost::asio::error::eof))
            {
                // Connection was dropped, re-connect to the service.
                error = ConnectToPeer(socket, endpoint_iterator);
                if (error && error == make_error_code(boost::system::errc::host_unreachable))
                {
                    TerminateProgram();
                }
                continue;
            }
            else 
            {
                cerr << error.message() << endl;
                retry++;
                continue;
            }
        }

        // Examine the response message.
        if (strncmp(response.data(), "normal", 6) != 0)
        {
            retry++;

            // If we received the lockdown response, then terminate.
            if (strncmp(response.data(), "lockdown", 8) == 0)
            {
                break;
            }

            // Not an expected response, potential error, retry to see if it was merely an aberration.
            continue;
        }

        // If we arrived here, the exchange was successful; reset the retry count.
        if (retry > 0)
        {
            retry = 0;
        }
    }

    // If retry count was incremented, then we have likely encountered an issue; shut things down.
    if (retry != 0)
    {
        TerminateProgram();
    }
}

当一个streambuf is provided directly to an I/O operation as the buffer, then the I/O operation will manage the input sequence appropriately by either commiting read data or consuming写入数据。因此,在以下代码中,command 在第一次迭代后为空:

boost::asio::streambuf command;
std::ostream command_stream(&command);
command_stream << "status\n";
// `command`'s input sequence contains "status\n".

while (retry < maxTriesBeforeAbort)
{
  ...

  // write all of `command`'s input sequence to the socket.
  boost::asio::write(socket, command, error);
  // `command.size()` is 0, as the write operation will consume the data.
  // Subsequent write operations with `command` will be no-ops.

  ...
}

一种解决方案是使用 std::string 作为缓冲区:

std::string command("status\n");

while (retry < maxTriesBeforeAbort)
{
  ...

  boost::asio::write(socket, boost::asio::buffer(command), error);

  ...
}

有关 streambuf 用法的更多详细信息,请考虑阅读 答案。