gpt4 book ai didi

c++ - 从 boost 套接字接收数据问题

转载 作者:太空狗 更新时间:2023-10-29 22:52:31 25 4
gpt4 key购买 nike

我通过 boost 网络创建了一个服务器并且它运行良好但是当我将连接到它的客户端存储在一个 std::map 中时,然后循环所有映射并从它们接收它给我段错误,这是回溯(gdb ):

Program received signal SIGSEGV, Segmentation fault.
boost::asio::basic_stream_socket<boost::asio::ip::tcp, boost::asio::stream_sock
t_service<boost::asio::ip::tcp> >::read_some<boost::asio::mutable_buffers_1>
(this=0x153fe48, buffers=@0x22fa48, ec=@0x22fa50)
at D:/Dev-Cpp/include/boost/asio/detail/win_iocp_socket_service.hpp:294
294 {
(gdb) bt
#0 boost::asio::basic_stream_socket<boost::asio::ip::tcp, boost::asio::stream_
ocket_service<boost::asio::ip::tcp> >::read_some<boost::asio::mutable_buffers_1
(this=0x153fe48, buffers=@0x22fa48, ec=@0x22fa50)
at D:/Dev-Cpp/include/boost/asio/detail/win_iocp_socket_service.hpp:294
#1 0x0040c825 in Client::receive (this=0x3d3fd0) at client.cpp:26
#2 0x00401913 in main (argc=1, argv=0x3d2568)
at D:/Dev-Cpp/Bin/../lib/gcc/mingw32/3.4.5/../../../../include/c++/3.4.5/bi
s/basic_string.h:1456
(gdb)

我的客户端.cpp:

#include "client.h"
#include <iostream>
#include <boost/array.hpp>

Client::Client(boost::asio::ip::tcp::socket* _sock)
: sock(_sock)
{
//
}

Client::~Client()
{
//
}

void Client::send(const std::string& msg)
{
boost::asio::write(*sock, boost::asio::buffer(msg, msg.length()));
}

std::string Client::receive()
{
boost::array<char, 1024> buffer;
boost::system::error_code err;
sock->read_some(boost::asio::buffer(buffer), err);
if (err == boost::asio::error::eof)
return std::string();

return std::string(buffer.data());
}

我该怎么办?

最佳答案

试试这个,限制读入你的 read_some 缓冲区的数据量:

sock->read_some(boost::asio::buffer(buffer, 1024), err);

您也可以直接使用 std::string 重载:

std::string buffer(1024, 0);
sock->read_some(boost::asio::buffer(buffer, 1024), err);
return buffer;

关于c++ - 从 boost 套接字接收数据问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4136770/

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