提升 ASIO 服务器分段故障

boost ASIO server segmentation fault

本文关键字:故障 分段 服务器 ASIO 提升      更新时间:2023-10-16

我用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 对象构造acceptor

只需对类内的声明重新排序即可。 令人惊讶的是,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();
    }

};