簡體   English   中英

提升ASIO服務器分段故障

[英]boost ASIO server segmentation fault

我使用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_acceptor之前m_ioService和使用未初始化的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();
    }


};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM