예제 1: 정적 소스를 사용한 직접 연결
- 소스 오브젝트 만들기
이 소스 객체를 생성하려면 먼저 정의 파일
simpleswitch.rep
을 생성합니다. 이 파일은 오브젝트의 프로퍼티와 메서드를 설명하며 Qt Remote Objects 컴파일러에 입력됩니다. 이 파일은 레플리카에 노출하는 데 필요한 인터페이스만 정의합니다.simpleswitch.rep
class SimpleSwitch { PROP(bool currState=false); SLOT(server_slot(bool clientState)); };
simpleswitch.rep
에서 ,currState
는 스위치의 현재 상태를 유지합니다.server_slot()
를 사용하면 소스와 상호 작용할 수 있으며echoSwitchState(bool newstate)
신호에 연결됩니다.
repc가 이 파일을 처리하도록 하려면
cmake
파일에 다음 줄을 추가하세요:qt6_add_repc_sources(directconnectserver simpleswitch.rep )
qmake
을 사용하는 경우REPC_SOURCE = simpleswitch.rep
이 지침은 Qt Remote Objects 모듈에만 해당되므로 프로젝트에도 추가해야 합니다. CMake를 사용 중이라면 추가하세요:
find_package(Qt6 REQUIRED COMPONENTS RemoteObjects) target_link_libraries(directconnectserver PRIVATE Qt6::RemoteObjects)
qmake
을 사용하는 경우QT += remoteobjects
repc는 지정한 빌드 디렉터리에
rep_SimpleSwitch_source.h
헤더를 만듭니다. 자세한 내용은 소스를 참조하세요.repc는 QtRO와 함께 사용할 세 가지 헬퍼 클래스를 생성합니다. 이 예제에서는 기본 클래스인
SimpleSwitchSimpleSource
을 사용합니다.rep_SimpleSwitch_source.h
에 정의된 추상 클래스입니다. 이 클래스에서 파생하여 아래와 같이 SimpleSwitch 구현 클래스를 정의합니다:simpleswitch.h
#ifndef SIMPLESWITCH_H #define SIMPLESWITCH_H #include "rep_simpleswitch_source.h" class SimpleSwitch : public SimpleSwitchSimpleSource { Q_OBJECT public: SimpleSwitch(QObject *parent = nullptr); ~SimpleSwitch(); void server_slot(bool clientState) override; public Q_SLOTS: void timeout_slot(); private: QTimer *stateChangeTimer; }; #endif
simpleswitch.h
에서,stateChangeTimer
는 SimpleSwitch의 상태를 토글하는 데 사용되는 QTimer 입니다.timeout_slot()
는stateChangeTimer
의 timeout() 신호에 연결됩니다.server_slot()
- 는 레플리카가 해당 슬롯 버전을 호출할 때마다 소스에서 자동으로 호출되며 수신된 값을 출력합니다.currStateChanged(bool)
currState
이 토글될 때마다 repc에서 생성된rep_SimpleSwitch_source.h
에 정의된 값을 출력합니다. 이 예제에서는 소스 측의 신호를 무시하고 나중에 레플리카 측에서 처리합니다.
SwitchState
클래스의 정의는 아래와 같습니다:simpleswitch.cpp
#include "simpleswitch.h"// 생성자SimpleSwitch::SimpleSwitch(QObject *부모) : SimpleSwitchSimpleSource(parent) { stateChangeTimer = new QTimer(this); // 타이머 초기화 QObject::connect(stateChangeTimer, &.QTimer::timeout, this, &SimpleSwitch::timeout_slot); // stateChangeTimer의 timeout() 신호를 simpleSwitch의 timeout_slot()에 연결 stateChangeTimer->start(2000); // 타이머 시작 및 2초로 타임아웃 설정 qDebug() << "Source Node Started"; }//destructorSimpleSwitch::~SimpleSwitch() { stateChangeTimer->stop(); }void SimpleSwitch::server_slot(bool clientState){ qDebug() << "Replica state is " << clientState; // print switch state echoed back by client }void SimpleSwitch::timeout_slot() { // 타이머 타임아웃 시 호출되는 슬롯 if (currState()) // 현재 상태가 참인지 확인, currState()는 repc 생성된 rep_simpleswitch_source.h에 정의되어있습니다 setCurrState(false); // 상태를 거짓으로설정 elsesetCurrState(true); // 상태를 참으로 설정합니다. qDebug() << "Source State is "<<currState();
- 레지스트리
만들기이 예제에서는 노드 간 직접 연결을 사용하므로 이 단계는 생략할 수 있습니다.
호스트 노드 만들기
호스트노드는 아래와 같이 생성됩니다:
QRemoteObjectHost srcNode(QUrl(QStringLiteral("local:replica")));
- 호스트 소스 객체 및
리모팅다음 문은 소스 객체를 인스턴스화하고 이를 호스트에 전달하여 QtRO 네트워크에 객체를 표시하는 프로세스인 "리모팅"을 활성화합니다:
SimpleSwitch srcSwitch; // create simple switch srcNode.enableRemoting(&srcSwitch); // enable remoting
위에서 설명한 단계를 구현하는
main.cpp
파일의 내용은 다음과 같습니다:main.cpp
#include <QCoreApplication> #include "simpleswitch.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); SimpleSwitch srcSwitch; // create simple switch // Create host node without Registry: QRemoteObjectHost srcNode(QUrl(QStringLiteral("local:replica"))); srcNode.enableRemoting(&srcSwitch); // enable remoting/sharing return a.exec(); }
이 소스 측 프로젝트를 컴파일하고 실행합니다. 생성된 복제본이 없는 출력은 아래와 같이 2초마다
true
와false
사이를 전환하는 스위치 상태와 함께 표시됩니다.
다음 단계는 네트워크의 레플리카 측을 생성하는 단계로, 이 예제에서는 소스에서 스위치 상태를 가져와서 다시 에코합니다.
레플리카 코드
- repc를
- 사용하여 프로젝트에 레플리카
추가하기소스 쪽에서 했던 것과 동일한 API 정의 파일인
을SimpleSwitch.rep
사용하여 레플리카 헤더 파일을 만듭니다.
cmake
를 사용하는 경우 클라이언트 측cmake
파일에 다음 줄을 추가하여.rep
파일 입력을 지정합니다:qt6_add_repc_replicas(directconnectclient simpleswitch.rep )
qmake
사용하는 경우 클라이언트 측
.pro
파일에 다음 줄을 추가합니다:REPC_REPLICA = simpleswitch.rep
repc 도구는 빌드 디렉터리에
rep_SimpleSwitch_replica.h
파일을 생성합니다. 자세한 내용은 복제본을 참조하세요. - 소스 호스트 노드와 연결할 노드
만들기다음 코드는 네트워크에서 두 번째 노드를 인스턴스화하여 소스 호스트 노드와 연결합니다:
QRemoteObjectNode repNode; // create remote object node repNode.connectToNode(QUrl(QStringLiteral("local:replica"))); // connect with remote host node
- 노드의 acquire()를 호출하여 복제본에 대한 포인터를 만듭니다.
먼저 복제본을 인스턴스화합니다:
QSharedPointer<SimpleSwitchReplica> ptr; ptr.reset(repNode.acquire<SimpleSwitchReplica>()); // acquire replica of source from host node
참고: acquire()는 레플리카에 대한 포인터를 반환하지만 수명은 관리하지 않습니다. 이 예에서는 반환된 포인터를 QSharedPointer 또는 QScopedPointer 으로 래핑하여 포인터가 항상 올바르게 삭제되도록 하는 권장 프로세스를 보여 줍니다.
main.cpp
는 위에서 설명한 단계를 구현하고 객체를 인스턴스화합니다:main.cpp
#include <QCoreApplication> #include "client.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QSharedPointer<SimpleSwitchReplica> ptr; // shared pointer to hold source replica QRemoteObjectNode repNode; // create remote object node repNode.connectToNode(QUrl(QStringLiteral("local:replica"))); // connect with remote host node ptr.reset(repNode.acquire<SimpleSwitchReplica>()); // acquire replica of source from host node Client rswitch(ptr); // create client switch object and pass reference of replica to it return a.exec(); }
Client
클래스에 대한 전체 선언과 정의는 다음과 같습니다:client.h
#ifndef _CLIENT_H #define _CLIENT_H #include <QObject> #include <QSharedPointer> #include "rep_simpleswitch_replica.h" class Client : public QObject { Q_OBJECT public: Client(QSharedPointer<SimpleSwitchReplica> ptr); ~Client() override = default; void initConnections();// Function to connect signals and slots of source and client Q_SIGNALS: void echoSwitchState(bool switchState);// this signal is connected with server_slot(..) on the source object and echoes back switch state received from source public Q_SLOTS: void recSwitchState_slot(bool); // slot to receive source state private: bool clientSwitchState; // holds received server switch state QSharedPointer<SimpleSwitchReplica> reptr;// holds reference to replica }; #endif
client.cpp
#include "client.h"// 생성자Client::Client(QSharedPointer<SimpleSwitchReplica> ptr) : QObject(nullptr),reptr(ptr) { // 초기화 슬롯으로 초기화된 복제본의 신호를 연결합니다.initConnections(); // 복제본이 repc에서 생성되었으므로 // 직접 SimpleSwitchReplica 신호/슬롯에 연결 가능합니다.}void Client::initConnections() { // 신호와 슬롯 사이의 연결을 초기화하고 // 소스 복제 신호 currStateChanged()를 클라이언트 recSwitchState() 슬롯에 연결하여 소스 현재 상태를 받습니다 . QObject::connect(reptr.data(), &SimpleSwitchReplica::currStateChanged, this, &Client::recSwitchState_slot); // 클라이언트의 echoSwitchState(..) 신호를 레플리카의 server_slot(..)과 연결하여 수신 상태를 다시 에코합니다. QObject::connect(this, &Client::echoSwitchState, reptr.data(), &SimpleSwitchReplica::server_slot); }void Client::recSwitchState_slot(bool value){ qDebug() << "Received source state "<< value << reptr.data()->currState(); clientSwitchState = reptr.data()->currState(); Q_EMIT echoSwitchState(clientSwitchState); // 수신 상태를 서버로 다시 에코하는 신호 전송}
이 예제를 소스 측 예제와 함께 컴파일하고 실행하면 다음과 같은 출력이 생성됩니다:
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.