2017-11-24 12 views
0

C++ 초보자는 여기.다른 클래스에서 네트워크 기능에 액세스하는 가장 좋은 방법은 무엇입니까?

저는 리모트 서버로 명령을 보내고 원격 측정기로 원격 로봇을 보내는 로봇을 만드는 프로젝트에 참여함으로써 C++을 가르치려고합니다.

#ifndef TCPCOM_H 
#define TCPCOM_H 
#define BOOST_DATE_TIME_NO_LIB 
#include <boost/asio.hpp> 
#include <boost/interprocess/sync/interprocess_semaphore.hpp> 
#include <deque> 
#include <mutex> 
#include "COM.h" 

class TcpCom : public COM 
{ 

    public: 
     TcpCom() : io_srv(), tcpSocket(io_srv), remoteHost(""), remotePort(""), connectedToRemoteHost(false), outboundMsgQueue(), outboundMsgQueueMutex(), 
     messagesInOutboundMsgQueue(0), incomingMsgQueue(), incomingMsgQueueMutex() 
     {} 
     int initialize(); 
     void connectToRemoteHost(const std::string host, const std::string port); 
     void disconnectFromRemoteHost(); 
     bool messagesWaitingInIncomingMsgQueue(); 
     SoftwareBusMsg getMsgFromIncomingMsgQueue(); 
     void addMsgToOutboundMsgQueue(SoftwareBusMsg& sbMsg); 
     bool isConnected(); 

    private: 
     void writeOutboundMsgToSocket(); 
     void deserializeHeader(std::string headerStr, MsgHeader& msgHdr); 
     void addMessageToIncomingMsgQueue(SoftwareBusMsg& sbMsg); 
     void readIncomingMsgHeader(MsgHeader& msgHdr); 
     std::string readIncomingMsgData(uint32_t msgDataLength); 
     SoftwareBusMsg readMsgFromSocket(); 
     void incomingMsgThread(); 
     void outboundMsgThread(); 
     void startReadAndWriteThreads(); 

     boost::asio::io_service io_srv; 
     boost::asio::ip::tcp::socket tcpSocket; 
     std::string remoteHost; 
     std::string remotePort; 
     bool connectedToRemoteHost; 

     std::deque<std::string> outboundMsgQueue; 
     std::mutex outboundMsgQueueMutex; 
     boost::interprocess::interprocess_semaphore messagesInOutboundMsgQueue; 

     std::deque<SoftwareBusMsg> incomingMsgQueue; 
     std::mutex incomingMsgQueueMutex; 
     //boost::interprocess::interprocess_semaphore messagesInIncomingMsgQueue; 

}; 
#endif 

내가 같은 모터 제어에 대한 책임 것과 다른 클래스를 원하는 :

나는 메시지를 보내고 서버에서 메시지를 수신 소켓 연결 및 공공 기능을 포함하는 로봇에 TcpCom 클래스가 원격 측정/오류보고를 위해 서버에 메시지를 전송할 수있는 기능을 제공합니다. 여기서 잘못된 것일 수도 있지만, 서버에 메시지를 보낼 수있는 기능이 필요한 각 클래스에 TcpCom 클래스의 인스턴스를 직접 전달하는 것이 좋지 않은 것처럼 보입니다.

대신 TcpCom 클래스에 대한 참조 인 전용 멤버가있는 EventReporter 클래스를 만들려고했습니다. 이렇게하면 다양한 유형의 이벤트 (정보, 오류)를 처리하기위한 코드 캡슐화가 가능하며 초기화 된 'EventReporter'객체를 필요한 모든 것에 전달할 수 있습니다.

#include "TcpCom.hpp" 

class EventReporter 
{ 
    public: 
     EventReporter(TcpCom& tcpComIn) : tcpCom(tcpComIn) 
     {} 
     //Will contain call to tcpCom.addMsgToOutboundMsgQueue() 
     void reportEvent(std::string eventType, std::string message); 
    private: 
     TcpCom tcpCom; 
}; 

이 코드를 컴파일했을 때 나는 몇 가지 오류를 가지고 : 나의 새로운 클래스는 내가 전달하여 피할 수 있다고 생각하는 TcpCom의 사본을 만들려고 할 것 같은

error: use of deleted function 'TcpCom::TcpCom(const TcpCom&)' 

error: use of deleted function 'boost::asio::io_service(const boost::asio::io_service&)' 

같습니다 참조로.

TcpCom을 복사하지 않으려면 unique_ptr과 같이 사용해야합니까, 아니면 다른 클래스에서 네트워킹 기능에 액세스 할 수있는 더 나은 방법이 있습니까?

감사합니다.

답변

1

답변이 없거나 오타가되어 버려서 Asker가 내게 알려주도록합니다.

class EventReporter 
{ 
    public: 
     EventReporter(TcpCom& tcpComIn) : tcpCom(tcpComIn) 
     {} 
     //Will contain call to tcpCom.addMsgToOutboundMsgQueue() 
     void reportEvent(std::string eventType, std::string message); 
    private: 
     TcpCom tcpCom; //<- this is not a reference 
}; 

TcpCom tcpCom;에서

TcpCom의 인스턴스를 정의하고, 아스카으로 TcpCom을하지 않은 참조는로, 목록을 사용하는 그들에 좋은 (멤버 이니셜 라이저 목록에 있으므로, tcpCom(tcpComIn)를 원 진술 많은 C++ 프로그래머들은 더 이상 배우지 못한다고 생각하지만 존재하지 않는다고 생각합니다) 사본을 만듭니다. 매개 변수 목록에서 참조로 전달함으로써 피하려고합니다.

오류 메시지는 구성원 (std :: mutex가 최소한이어야하고 여러 뮤텍스 사본이 좋지 않음)이 TcpCom이므로 복사 할 수 없으므로 원하는 경우에도 복사 할 수 없습니다.

간단한 해결책은 아스 커 다른 uncopyable 객체는 다른 복사하지 않는

class EventReporter 
{ 
    public: 
     EventReporter(TcpCom& tcpComIn) : tcpCom(tcpComIn) 
     {} 
     //Will contain call to tcpCom.addMsgToOutboundMsgQueue() 
     void reportEvent(std::string eventType, std::string message); 
    private: 
     TcpCom & tcpCom; //<- change made here 
}; 

여기서 자신의 코드 또는하여 EventReporter 예를 그들이 갈 수 있어야한다 소스 TcpCom 오래 살 수 있습니다.

+0

내가 오타라고 말하지 않겠다. 나는 참조 (TcpCom & tcpComIn)를 전달하면 회원 (TcpCom tcpCom)도 참조가 될 것이라고 생각했다. TcpCom 확실히 EventReporter, 그래서이 솔루션을 잘해야합니다 :) – user3878723