gpt4 book ai didi

c++ - 如何使用 lambda 创建 ReadHandler

转载 作者:可可西里 更新时间:2023-11-01 02:46:25 30 4
gpt4 key购买 nike

我正在尝试使用 boost::asio 从 TCP 连接读取定义数量的字节,但 asio 不接受我提供给它的句柄。

#include <boost/asio.hpp>

int main(){
int port = 2222;
boost::asio::io_service io_service_;
boost::asio::ip::tcp::acceptor acceptor_(io_service_, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port));
char packet_type[4];

boost::asio::ip::tcp::socket socket_(io_service_);
acceptor_.async_accept(socket_, [&](boost::system::error_code ec){

boost::asio::async_read(socket_, boost::asio::buffer(packet_type, 4),
[](boost::system::error_code &ec, std::size_t N) // <- error
{

});
});
}

我得到的错误是:

error C2338: ReadHandler type requirements not met
: see reference to function template instantiation 'boost::asio::async_result<Handler>::type boost::asio::async_read<boost::asio::ip::tcp::socket,boost::asio::mutable_buffers_1,main::<lambda_3400466f101ccf7a8013d928754266a0>::()::<lambda_af1dbf92bb67c9e911b61eb3b897934f>>(AsyncReadStream &,const MutableBufferSequence &,ReadHandler &&)' being compiled
with
[
Handler=main::<lambda_3400466f101ccf7a8013d928754266a0>::()::<lambda_af1dbf92bb67c9e911b61eb3b897934f>,
AsyncReadStream=boost::asio::ip::tcp::socket,
MutableBufferSequence=boost::asio::mutable_buffers_1,
ReadHandler=main::<lambda_3400466f101ccf7a8013d928754266a0>::()::<lambda_af1dbf92bb67c9e911b61eb3b897934f>
]

如果我改用 socket_.async_read_some() 会工作得很好,但因为我想要读取固定数量的字节,所以效果不佳。

最佳答案

您不能通过可变引用获取错误代码:

    [](boost::system::error_code ec, std::size_t N) {}

    [](boost::system::error_code const& ec, std::size_t N) {}

Live On Coliru

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

int main(){
int port = 2222;
boost::asio::io_service io_service_;
boost::asio::ip::tcp::acceptor acceptor_(io_service_, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port));
char packet_type[4];

boost::asio::ip::tcp::socket socket_(io_service_);
acceptor_.async_accept(socket_, [&](boost::system::error_code ec){

boost::asio::async_read(socket_, boost::asio::buffer(packet_type, 4),
[&](boost::system::error_code ec, std::size_t N)
{
std::cout << "Received: '";
std::cout.write(packet_type, sizeof(packet_type)) << "'\n";
});
});

io_service_.run();
}

打印

g++ -std=c++11 -O2 -Wall -pedantic -pthread main.cpp -lboost_system -lboost_thread
./a.out& sleep 1; nc 127.0.0.1 2222 <<< halp

Received: 'halp'

关于c++ - 如何使用 lambda 创建 ReadHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33088088/

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