我使用 Boost ASIO 创建了一个服务器。它构建良好,但一旦我运行它,它就会出现段错误。无法真正弄清楚这种行为。
另外,我读到这可能是因为我没有明确初始化 io_service 对象。如果是这种情况,那么我该如何修改这段代码,这样我就不必从类外部传递 io_service 对象。
下面是我的代码:
#include <iostream>
#include <string>
#include <memory>
#include <array>
#include <boost/asio.hpp>
using namespace boost::asio;
//Connection Class
class Connection : public std::enable_shared_from_this<Connection>{
ip::tcp::socket m_socket;
std::array<char, 2056> m_acceptMessage;
std::string m_acceptMessageWrapper;
std::string m_buffer;
public:
Connection(io_service& ioService): m_socket(ioService) { }
virtual ~Connection() { }
static std::shared_ptr<Connection> create(io_service& ioService){
return std::shared_ptr<Connection>(new Connection(ioService));
}
std::string& receiveMessage() {
size_t len = boost::asio::read(m_socket, boost::asio::buffer(m_acceptMessage));
m_acceptMessageWrapper = std::string(m_acceptMessage.begin(), m_acceptMessage.begin() + len);
return m_acceptMessageWrapper;
}
void sendMessage(const std::string& message) {
boost::asio::write(m_socket, boost::asio::buffer(message));
}
ip::tcp::socket& getSocket(){
return m_socket;
}
};
//Server Class
class Server {
ip::tcp::acceptor m_acceptor;
io_service m_ioService ;
public:
Server(int port):
m_acceptor(m_ioService, ip::tcp::endpoint(ip::tcp::v4(), port)){ }
virtual ~Server() { }
std::shared_ptr<Connection> createConnection(){
std::shared_ptr<Connection> newConnection = Connection::create(m_ioService);
m_acceptor.accept(newConnection->getSocket());
return newConnection;
}
void runService() {
m_ioService.run();
}
};
int main(int argc, char* argv[]) {
Server s(5000);
auto c1 = s.createConnection();
//do soething
s.runService();
return 0;
}
最佳答案
您面临初始化顺序问题。在您的类 Server
中,您在 m_ioService
之前声明了 m_acceptor
并使用未初始化的 io_service
对象来构造 接受者
。
只需重新排列类内的声明即可。令人惊讶的是 clang
并没有为此给出任何警告。
class Server {
io_service m_ioService ;
ip::tcp::acceptor m_acceptor;
public:
Server(int port):
m_acceptor(m_ioService, ip::tcp::endpoint(ip::tcp::v4(), port)){ }
virtual ~Server() { }
std::shared_ptr<Connection> createConnection(){
std::shared_ptr<Connection> newConnection = Connection::create(m_ioService);
m_acceptor.accept(newConnection->getSocket());
return newConnection;
}
void runService() {
m_ioService.run();
}
};
关于c++ - boost ASIO 服务器段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41540264/