我通过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)
我的client.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());
}
我该怎么办?
答案 0 :(得分:2)
尝试此操作,以限制读入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;