gpt4 book ai didi

c++ - async_read 不读取从 telnet 发送的数据

转载 作者:行者123 更新时间:2023-11-30 02:53:30 26 4
gpt4 key购买 nike

这是我当前的服务器代码。我使用 telnet 连接到服务器。

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

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

class Connection
{
public:
Connection(boost::asio::io_service& io_service) : socket_(io_service)
{

}

void start()
{
AsyncRead();
}

tcp::socket& socket()
{
return socket_;
}
private:
void AsyncRead()
{
boost::asio::async_read(socket_, boost::asio::buffer(data_, max_length),
[this](boost::system::error_code ec, std::size_t length)
{
if (!ec)
{
std::cout << data_ << std::endl;
}
});
}

tcp::socket socket_;
enum { max_length = 1024 };
char data_[max_length];
};


class server
{
public:
server(boost::asio::io_service& io_service, short port)
: io_service_(io_service),
acceptor_(io_service, tcp::endpoint(tcp::v4(), port))
{
start_accept();
}

private:
void start_accept()
{
Connection* connection = new Connection(io_service_);
acceptor_.async_accept(connection->socket(), [this, connection](boost::system::error_code ec)
{
//std::cout << ec.message() << std::endl;
if(!ec)
{
std::cout << "Connected." << std::endl;
connection->start();
}
else
{
delete connection;
}

start_accept();
});
}

boost::asio::io_service& io_service_;
tcp::acceptor acceptor_;
};

int main(int argc, char* argv[])
{
try
{
boost::asio::io_service io_service;

server s(io_service, 7899);

io_service.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}

return 0;
}

我使用 async_read_some 而不是 async_read 我可以获得从 telnet 发送的第一条消息,仅此而已。

对我做错了什么有什么建议吗?
谢谢。

最佳答案

async_read 将读取长度参数中指定的字节数。您没有看到第一条消息,因为 async_read 仍在等待读取 max_length 字节。这question讨论类似的行为

关于c++ - async_read 不读取从 telnet 发送的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17948459/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com