QRPC examples
Below are some examples of how you can use QRPC. It is a simple example of a server that returns a QString with a fortune cookie saying.
Interface
Define the interface...
interface Fortune
{
method fortune() const returns QString;
}
Server
Add the idl file to your project. The code generator will generate all network communication code and an abstract interface to be implemented by a server object.
QRPC_SERVER_FILES = ../fortune.qrpcidl
Implement the interface...
#include "fortune.h"
#include <QStringList>
class FortuneImpl : public Fortune
{
public:
explicit FortuneImpl( QObject* parent = 0 );
~FortuneImpl();
virtual QString fortune() const;
private:
QStringList mFortunes;
};
Create server objects...
class Factory : public QRPC::ServerObjectFactory
{
public:
QRPC::ServerObject* createServer( const QString& name, QObject* parent=0 )
{
if ( name == "Fortune" )
return new FortuneImpl( parent );
return 0;
}
};
int main( int argc, char** argv )
{
QCoreApplication app( argc, argv );
// Register the FortuneImpl factory with the ServerObjectFactory
(new Factory)->registerFactory();
// Start a QRPC server
QRPC::OrbServer server;
server.listen( QHostAddress::LocalHost, 11111 );
return app.exec();
}
Client
Add the idl file to your project. The code generator will generate all network communication code and a class to represent a server object.
QRPC_CLIENT_FILES = ../fortune.qrpcidl
Communicate with the server...
int main( int argc, char** argv )
{
QCoreApplication app(argc, argv);
// Make the server object and connect to the server
try
{
Fortune server;
server.connectToServer( "localhost", 11111 );
while (true)
{
// Ask for a fortune
qDebug( "Fortune: %s", qPrintable( server.fortune() ) );
#ifdef Q_WS_WIN
Sleep(1000);
#else
sleep(1);
#endif
}
}
catch ( TC::Exception& e )
{
qDebug( "Exception caught: %s", qPrintable( e.message() ) );
return 1;
}
return 0;
}
