深入浅出Alljoyn——实例分析之远程调用(Method)篇
深入浅出就是很深入的学习了很久,还是只学了毛皮,呵呵!
服务端完整代码:
#include <qcc/platform.h> #include <assert.h>
#include <signal.h>
#include <stdio.h>
#include <vector> #include <qcc/String.h> #include <alljoyn/BusAttachment.h>
#include <alljoyn/DBusStd.h>
#include <alljoyn/AllJoynStd.h>
#include <alljoyn/BusObject.h>
#include <alljoyn/MsgArg.h>
#include <alljoyn/version.h> #include <alljoyn/Status.h> using namespace std;
using namespace qcc;
using namespace ajn; /*constants*/
static const char* INTERFACE_NAME = "org.alljoyn.Bus.sample";
static const char* SERVICE_NAME = "org.alljoyn.Bus.sample";
static const char* SERVICE_PATH = "/sample";
static const SessionPort SERVICE_PORT = ; static volatile sig_atomic_t s_interrupt = false; static void SigIntHandler(int sig)
{
s_interrupt = true;
} class BasicSampleObject : public BusObject {
public:
BasicSampleObject(BusAttachment& bus, const char* path) :
BusObject(path)
{
/** Add the test interface to this object */
const InterfaceDescription* exampleIntf = bus.GetInterface(INTERFACE_NAME);
assert(exampleIntf);
AddInterface(*exampleIntf); /** Register the method handlers with the object */
const MethodEntry methodEntries[] = {
{ exampleIntf->GetMember("cat"), static_cast<MessageReceiver::MethodHandler>(&BasicSampleObject::Cat) }
};
QStatus status = AddMethodHandlers(methodEntries, sizeof(methodEntries) / sizeof(methodEntries[]));
if (ER_OK != status) {
printf("Failed to register method handlers for BasicSampleObject.\n");
}
} void ObjectRegistered()
{
BusObject::ObjectRegistered();
printf("ObjectRegistered has been called.\n");
} void Cat(const InterfaceDescription::Member* member, Message& msg)
{
/* Concatenate the two input strings and reply with the result. */
qcc::String inStr1 = msg->GetArg()->v_string.str;
qcc::String inStr2 = msg->GetArg()->v_string.str;
qcc::String outStr = inStr1 + inStr2; MsgArg outArg("s", outStr.c_str());
QStatus status = MethodReply(msg, &outArg, );
if (ER_OK != status) {
printf("Ping: Error sending reply.\n");
}
}
}; class MyBusListener : public BusListener, public SessionPortListener {
void NameOwnerChanged(const char* busName, const char* previousOwner, const char* newOwner)
{
if (newOwner && ( == strcmp(busName, SERVICE_NAME))) {
printf("NameOwnerChanged: name=%s, oldOwner=%s, newOwner=%s.\n",
busName,
previousOwner ? previousOwner : "<none>",
newOwner ? newOwner : "<none>");
}
}
bool AcceptSessionJoiner(SessionPort sessionPort, const char* joiner, const SessionOpts& opts)
{
if (sessionPort != SERVICE_PORT) {
printf("Rejecting join attempt on unexpected session port %d.\n", sessionPort);
return false;
}
printf("Accepting join session request from %s (opts.proximity=%x, opts.traffic=%x, opts.transports=%x).\n",
joiner, opts.proximity, opts.traffic, opts.transports);
return true;
}
}; /** The bus listener object. */
static MyBusListener s_busListener; /** Top level message bus object. */
static BusAttachment* s_msgBus = NULL; /** Create the interface, report the result to stdout, and return the result status. */
QStatus CreateInterface(void)
{
/* Add org.alljoyn.Bus.method_sample interface */
InterfaceDescription* testIntf = NULL;
QStatus status = s_msgBus->CreateInterface(INTERFACE_NAME, testIntf); if (status == ER_OK) {
printf("Interface created.\n");
testIntf->AddMethod("cat", "ss", "s", "inStr1,inStr2,outStr", );
testIntf->Activate();
} else {
printf("Failed to create interface '%s'.\n", INTERFACE_NAME);
} return status;
} /** Register the bus object and connect, report the result to stdout, and return the status code. */
QStatus RegisterBusObject(BasicSampleObject* obj)
{
QStatus status = s_msgBus->RegisterBusObject(*obj); if (ER_OK == status) {
printf("RegisterBusObject succeeded.\n");
} else {
printf("RegisterBusObject failed (%s).\n", QCC_StatusText(status));
} return status;
} /** Connect, report the result to stdout, and return the status code. */
QStatus ConnectBusAttachment(void)
{
QStatus status = s_msgBus->Connect(); if (ER_OK == status) {
printf("Connect to '%s' succeeded.\n", s_msgBus->GetConnectSpec().c_str());
} else {
printf("Failed to connect to '%s' (%s).\n", s_msgBus->GetConnectSpec().c_str(), QCC_StatusText(status));
} return status;
} /** Start the message bus, report the result to stdout, and return the status code. */
QStatus StartMessageBus(void)
{
QStatus status = s_msgBus->Start(); if (ER_OK == status) {
printf("BusAttachment started.\n");
} else {
printf("Start of BusAttachment failed (%s).\n", QCC_StatusText(status));
} return status;
} /** Create the session, report the result to stdout, and return the status code. */
QStatus CreateSession(TransportMask mask)
{
SessionOpts opts(SessionOpts::TRAFFIC_MESSAGES, false, SessionOpts::PROXIMITY_ANY, mask);
SessionPort sp = SERVICE_PORT;
QStatus status = s_msgBus->BindSessionPort(sp, opts, s_busListener); if (ER_OK == status) {
printf("BindSessionPort succeeded.\n");
} else {
printf("BindSessionPort failed (%s).\n", QCC_StatusText(status));
} return status;
} /** Advertise the service name, report the result to stdout, and return the status code. */
QStatus AdvertiseName(TransportMask mask)
{
QStatus status = s_msgBus->AdvertiseName(SERVICE_NAME, mask); if (ER_OK == status) {
printf("Advertisement of the service name '%s' succeeded.\n", SERVICE_NAME);
} else {
printf("Failed to advertise name '%s' (%s).\n", SERVICE_NAME, QCC_StatusText(status));
} return status;
} /** Request the service name, report the result to stdout, and return the status code. */
QStatus RequestName(void)
{
const uint32_t flags = DBUS_NAME_FLAG_REPLACE_EXISTING | DBUS_NAME_FLAG_DO_NOT_QUEUE;
QStatus status = s_msgBus->RequestName(SERVICE_NAME, flags); if (ER_OK == status) {
printf("RequestName('%s') succeeded.\n", SERVICE_NAME);
} else {
printf("RequestName('%s') failed (status=%s).\n", SERVICE_NAME, QCC_StatusText(status));
} return status;
} /** Wait for SIGINT before continuing. */
void WaitForSigInt(void)
{
while (s_interrupt == false) {
#ifdef _WIN32
Sleep();
#else
usleep( * );
#endif
}
} /** Main entry point */
int main(int argc, char** argv, char** envArg)
{
printf("AllJoyn Library version: %s.\n", ajn::GetVersion());
printf("AllJoyn Library build info: %s.\n", ajn::GetBuildInfo()); /* Install SIGINT handler */
signal(SIGINT, SigIntHandler); QStatus status = ER_OK; /* Create message bus */
s_msgBus = new BusAttachment("myApp", true); if (!s_msgBus) {
status = ER_OUT_OF_MEMORY;
} if (ER_OK == status) {
status = CreateInterface();
} if (ER_OK == status) {
s_msgBus->RegisterBusListener(s_busListener);
} if (ER_OK == status) {
status = StartMessageBus();
} BasicSampleObject testObj(*s_msgBus, SERVICE_PATH); if (ER_OK == status) {
status = RegisterBusObject(&testObj);
} if (ER_OK == status) {
status = ConnectBusAttachment();
} /*
* Advertise this service on the bus.
* There are three steps to advertising this service on the bus.
* 1) Request a well-known name that will be used by the client to discover
* this service.
* 2) Create a session.
* 3) Advertise the well-known name.
*/
if (ER_OK == status) {
status = RequestName();
} const TransportMask SERVICE_TRANSPORT_TYPE = TRANSPORT_ANY; if (ER_OK == status) {
status = CreateSession(SERVICE_TRANSPORT_TYPE);
} if (ER_OK == status) {
status = AdvertiseName(SERVICE_TRANSPORT_TYPE);
} /* Perform the service asynchronously until the user signals for an exit. */
if (ER_OK == status) {
WaitForSigInt();
} /* Clean up msg bus */
delete s_msgBus;
s_msgBus = NULL; printf("Basic service exiting with status 0x%04x (%s).\n", status, QCC_StatusText(status)); return (int) status;
}
服务端主流程解析:
int main(int argc, char** argv, char** envArg)
{
/* 注册系统信号回调函数*/
signal(SIGINT, SigIntHandler); /* 创建Bus连接器 */
s_msgBus = new BusAttachment("myApp", true); /* 创建object 的接口*/
status = CreateInterface(); /*绑定总线监听器*/
s_msgBus->RegisterBusListener(s_busListener); /*开启总线*/
status = StartMessageBus(); /*实例化对象*/
BasicSampleObject testObj(*s_msgBus, SERVICE_PATH); /*总线附件上注册对象*/
status = RegisterBusObject(&testObj); /*连接到总线上*/
status = ConnectToDaemon(); /*请求一个服务名即wellknow name*/
status = RequestName(); const TransportMask SERVICE_TRANSPORT_TYPE = TRANSPORT_ANY; /*创建一个会话*/
status = CreateSession(SERVICE_TRANSPORT_TYPE); /*在总线上广播服务名*/
status = AdvertiseName(SERVICE_TRANSPORT_TYPE); /* 等待用户终止 */
WaitForSigInt(); /* 释放资源 */
delete s_msgBus;
s_msgBus = NULL; return (int) status;
}
客户端完整代码:
#include <qcc/platform.h> #include <assert.h>
#include <signal.h>
#include <stdio.h>
#include <vector> #include <qcc/String.h> #include <alljoyn/BusAttachment.h>
#include <alljoyn/version.h>
#include <alljoyn/AllJoynStd.h>
#include <alljoyn/Status.h> using namespace std;
using namespace qcc;
using namespace ajn; /** Static top level message bus object */
static BusAttachment* g_msgBus = NULL; /*constants*/
static const char* INTERFACE_NAME = "org.alljoyn.Bus.sample";
static const char* SERVICE_NAME = "org.alljoyn.Bus.sample";
static const char* SERVICE_PATH = "/sample";
static const SessionPort SERVICE_PORT = ; static bool s_joinComplete = false;
static SessionId s_sessionId = ; static volatile sig_atomic_t s_interrupt = false; static void SigIntHandler(int sig)
{
s_interrupt = true;
} /** AllJoynListener receives discovery events from AllJoyn */
class MyBusListener : public BusListener, public SessionListener {
public:
void FoundAdvertisedName(const char* name, TransportMask transport, const char* namePrefix)
{
if ( == strcmp(name, SERVICE_NAME)) {
printf("FoundAdvertisedName(name='%s', prefix='%s')\n", name, namePrefix); /* We found a remote bus that is advertising basic service's well-known name so connect to it. */
/* Since we are in a callback we must enable concurrent callbacks before calling a synchronous method. */
g_msgBus->EnableConcurrentCallbacks();
SessionOpts opts(SessionOpts::TRAFFIC_MESSAGES, false, SessionOpts::PROXIMITY_ANY, TRANSPORT_ANY);
QStatus status = g_msgBus->JoinSession(name, SERVICE_PORT, this, s_sessionId, opts);
if (ER_OK == status) {
printf("JoinSession SUCCESS (Session id=%d).\n", s_sessionId);
} else {
printf("JoinSession failed (status=%s).\n", QCC_StatusText(status));
}
}
s_joinComplete = true;
} void NameOwnerChanged(const char* busName, const char* previousOwner, const char* newOwner)
{
if (newOwner && ( == strcmp(busName, SERVICE_NAME))) {
printf("NameOwnerChanged: name='%s', oldOwner='%s', newOwner='%s'.\n",
busName,
previousOwner ? previousOwner : "<none>",
newOwner ? newOwner : "<none>");
}
}
}; /** Create the interface, report the result to stdout, and return the result status. */
QStatus CreateInterface(void)
{
/* Add org.alljoyn.Bus.method_sample interface */
InterfaceDescription* testIntf = NULL;
QStatus status = g_msgBus->CreateInterface(INTERFACE_NAME, testIntf); if (status == ER_OK) {
printf("Interface '%s' created.\n", INTERFACE_NAME);
testIntf->AddMethod("cat", "ss", "s", "inStr1,inStr2,outStr", );
testIntf->Activate();
} else {
printf("Failed to create interface '%s'.\n", INTERFACE_NAME);
} return status;
} /** Start the message bus, report the result to stdout, and return the result status. */
QStatus StartMessageBus(void)
{
QStatus status = g_msgBus->Start(); if (ER_OK == status) {
printf("BusAttachment started.\n");
} else {
printf("BusAttachment::Start failed.\n");
} return status;
} /** Handle the connection to the bus, report the result to stdout, and return the result status. */
QStatus ConnectToBus(void)
{
QStatus status = g_msgBus->Connect(); if (ER_OK == status) {
printf("BusAttachment connected to '%s'.\n", g_msgBus->GetConnectSpec().c_str());
} else {
printf("BusAttachment::Connect('%s') failed.\n", g_msgBus->GetConnectSpec().c_str());
} return status;
} /** Register a bus listener in order to get discovery indications and report the event to stdout. */
void RegisterBusListener(void)
{
/* Static bus listener */
static MyBusListener s_busListener; g_msgBus->RegisterBusListener(s_busListener);
printf("BusListener Registered.\n");
} /** Begin discovery on the well-known name of the service to be called, report the result to
stdout, and return the result status. */
QStatus FindAdvertisedName(void)
{
/* Begin discovery on the well-known name of the service to be called */
QStatus status = g_msgBus->FindAdvertisedName(SERVICE_NAME); if (status == ER_OK) {
printf("org.alljoyn.Bus.FindAdvertisedName ('%s') succeeded.\n", SERVICE_NAME);
} else {
printf("org.alljoyn.Bus.FindAdvertisedName ('%s') failed (%s).\n", SERVICE_NAME, QCC_StatusText(status));
} return status;
} /** Wait for join session to complete, report the event to stdout, and return the result status. */
QStatus WaitForJoinSessionCompletion(void)
{
unsigned int count = ; while (!s_joinComplete && !s_interrupt) {
if ( == (count++ % )) {
printf("Waited %u seconds for JoinSession completion.\n", count / );
} #ifdef _WIN32
Sleep();
#else
usleep( * );
#endif
} return s_joinComplete && !s_interrupt ? ER_OK : ER_ALLJOYN_JOINSESSION_REPLY_CONNECT_FAILED;
} /** Do a method call, report the result to stdout, and return the result status. */
QStatus MakeMethodCall(void)
{
ProxyBusObject remoteObj(*g_msgBus, SERVICE_NAME, SERVICE_PATH, s_sessionId);
const InterfaceDescription* alljoynTestIntf = g_msgBus->GetInterface(INTERFACE_NAME); assert(alljoynTestIntf);
remoteObj.AddInterface(*alljoynTestIntf); Message reply(*g_msgBus);
MsgArg inputs[]; inputs[].Set("s", "Hello ");
inputs[].Set("s", "World!"); QStatus status = remoteObj.MethodCall(SERVICE_NAME, "cat", inputs, , reply, ); if (ER_OK == status) {
printf("'%s.%s' (path='%s') returned '%s'.\n", SERVICE_NAME, "cat",
SERVICE_PATH, reply->GetArg()->v_string.str);
} else {
printf("MethodCall on '%s.%s' failed.", SERVICE_NAME, "cat");
} return status;
} /** Main entry point */
int main(int argc, char** argv, char** envArg)
{
printf("AllJoyn Library version: %s.\n", ajn::GetVersion());
printf("AllJoyn Library build info: %s.\n", ajn::GetBuildInfo()); /* Install SIGINT handler. */
signal(SIGINT, SigIntHandler); QStatus status = ER_OK; /* Create message bus. */
g_msgBus = new BusAttachment("myApp", true); /* This test for NULL is only required if new() behavior is to return NULL
* instead of throwing an exception upon an out of memory failure.
*/
if (!g_msgBus) {
status = ER_OUT_OF_MEMORY;
} if (ER_OK == status) {
status = CreateInterface();
} if (ER_OK == status) {
status = StartMessageBus();
} if (ER_OK == status) {
status = ConnectToBus();
} if (ER_OK == status) {
RegisterBusListener();
status = FindAdvertisedName();
} if (ER_OK == status) {
status = WaitForJoinSessionCompletion();
} if (ER_OK == status) {
status = MakeMethodCall();
} /* Deallocate bus */
delete g_msgBus;
g_msgBus = NULL; printf("Basic client exiting with status 0x%04x (%s).\n", status, QCC_StatusText(status)); return (int) status;
}
客户端主流程解析:
int main(int argc, char** argv, char** envArg)
{
printf("AllJoyn Library version: %s.\n", ajn::GetVersion());
printf("AllJoyn Library build info: %s.\n", ajn::GetBuildInfo()); /* 注册系统信号回调函数*/
signal(SIGINT, SigIntHandler); QStatus status = ER_OK; /* 创建Bus连接器 */
g_msgBus = new BusAttachment("myApp", true); /* This test for NULL is only required if new() behavior is to return NULL
* instead of throwing an exception upon an out of memory failure.
*/
if (!g_msgBus) {
status = ER_OUT_OF_MEMORY;
}
/* 创建object 的接口*/
if (ER_OK == status) {
status = CreateInterface();
}
/*开启总线*/
if (ER_OK == status) {
status = StartMessageBus();
}
/*连接到总线上*/ if (ER_OK == status) {
status = ConnectToBus();
} if (ER_OK == status) {
RegisterBusListener();/*绑定总线监听器*/
status = FindAdvertisedName();/*在总线上发现服务名*/
} if (ER_OK == status) {
status = WaitForJoinSessionCompletion();
} /*远程调用方法*/ if (ER_OK == status) {
status = MakeMethodCall();
} /* 释放资源 */
delete g_msgBus;
g_msgBus = NULL; printf("Basic client exiting with status 0x%04x (%s).\n", status, QCC_StatusText(status)); return (int) status;
}
通信过程中比较重要的几点:
1、 接口由bus连接器创建和保存所以创建的实例
2、 对象具体实现接口的属性(方法,属性和信号),与具体接口绑定,作为对象对外的接口。(可以含有多个接口)
3、连接总线s_msgBus->Connect()是通过dbus方式实现的,利用了dbus中现存的方法和消息。
用下面的图可能表达的更清楚:
通过Bus建立好连接后,服务端的object提供接口比如说方法, 那么客户端的object只需产生一个object的代理,即可调用服务端的object提供接口,是不是比较好玩。
服务端方法调用的代码:
服务端:通过接受客户端提供的参数,并通过MethodReply()给客户端返回结果
void Cat(const InterfaceDescription::Member* member, Message& msg)
{
/* Concatenate the two input strings and reply with the result. */
qcc::String inStr1 = msg->GetArg()->v_string.str;
qcc::String inStr2 = msg->GetArg()->v_string.str;
qcc::String outStr = inStr1 + inStr2; MsgArg outArg("s", outStr.c_str());
QStatus status = MethodReply(msg, &outArg, );
if (ER_OK != status) {
printf("Ping: Error sending reply.\n");
}
}
客户端方法调用的代码:
QStatus status = remoteObj.MethodCall(SERVICE_NAME, "cat", inputs, , reply, );
说了这么多,这个代码的作用是干嘛呢,就是服务端提供一个连接字符串(str1+str2)的方法,并将结果返回给客户端。当然这只是一个很简单sample,如果你将你家电视定义了换台方法的话,用手机就可以通过调用这个方法进行控制了,当然前提是你的电视和手机在一个网内!
一个人学习有时挺没意思的,那就加入q群49073007一起交流讨论吧。
深入浅出Alljoyn——实例分析之远程调用(Method)篇的更多相关文章
- Openstack Nova 源码分析 — RPC 远程调用过程
目录 目录 Nova Project Services Project 的程序入口 setuppy Nova中RPC远程过程调用 nova-compute RPC API的实现 novacompute ...
- Delphi实例分析:远程传输数据和文件
在Windows操作系统的平台上,WinSock是首选的网络编程接口,用于在网络上传输数据和交换信息,它构成了Windows操作系统进行网络编程的基础.对于编写网络应用程序来说,WinSock是一门非 ...
- 《Spring技术内幕》学习笔记17——Spring HTTP调用器实现远程调用
1.Spring中,HTTPInvoker(HTTP调用器)是通过基于HTTP协议的分布式远程调用解决方案,和java RMI一样,HTTP调用器也需要使用java的对象序列化机制完成客户端和服务器端 ...
- 【spring源码学习】spring的远程调用实现源码分析
[一]spring的远程调用提供的基础类 (1)org.springframework.remoting.support.RemotingSupport ===>spring提供实现的远程调用客 ...
- Android 学习笔记之WebService实现远程调用+内部原理分析...
PS:终于可以抽出时间写写博客了,忙着学校的三周破实训外加替考...三周了,没怎么学习...哎... 学习内容: 1.WebService 实现远程方法的调用 什么是WebService... ...
- RPC原理及RPC实例分析
在学校期间大家都写过不少程序,比如写个hello world服务类,然后本地调用下,如下所示.这些程序的特点是服务消费方和服务提供方是本地调用关系. 1 2 3 4 5 6 public class ...
- RPC-原理及RPC实例分析
还有就是:RPC支持的BIO,NIO的理解 (1)BIO: Blocking IO;同步阻塞: (2)NIO:Non-Blocking IO, 同步非阻塞; 参考:IO多路复用,同步,异步,阻塞和非阻 ...
- Dubbo源码学习总结系列二 dubbo-rpc远程调用模块
dubbo本质是一个RPC框架,我们首先讨论这个骨干中的骨干,dubbo-rpc模块. 主要讨论一下几部分内容: 一.此模块在dubbo整体框架中的作用: 二.此模块需要完成的需求功能点及接口定义: ...
- RPC原理及RPC实例分析(转)
出处:https://my.oschina.net/hosee/blog/711632 在学校期间大家都写过不少程序,比如写个hello world服务类,然后本地调用下,如下所示.这些程序的特点是服 ...
随机推荐
- OpenMesh 将默认的 float 类型改为 double 类型
OpenMesh 中默认的数据类型都是 float 类型的,如果要将其默认的 float 类型改为 double 类型,可以这么做: #include <OpenMesh/Core/Mesh/P ...
- 制作bat脚本,抓取Android设备logcat
::bat制作抓取Android设备的logcat,并保存以时间命名的txt文件至设备目录 1 @ECHO off adb wait-for-device ECHO 正在连接设备 adb logcat ...
- Dev GridView行拖拽
http://blog.csdn.net/keyrainie/article/details/8513802 http://www.cnblogs.com/qq4004229/archive/2012 ...
- Windows - 性能监控之磁盘剩余空间大小警报
开始 -> 运行 -> 键入命令 perfmon.msc 数据收集器(Data Collector Sets) -> 用户自定义(User Defined)
- 数组中pop()和reverse()方法调用
数组的倒序排列,可以采用reverse()和pop()方法进行排列.
- 用js把数据从一个页面传到另一个页面
用js把数据从一个页面传到另一个页面的层里? 如果是传到新页面的话,你网站基于什么语言开发直接用get或者post获取,然后输出到这个层 通过url传参 如果是HTML页面的话JS传到新页面就wind ...
- 转:Delphi2010新发现-类的构造和析构函数功能
Delphi2010发布了. 虽然凭着对Delphi的热爱第一时间就安装了,但是现在可能是年纪大了,对新事物缺乏兴趣了.一直都没有仔细研究. 今天有点时间试了一下新功能. 本来C#和Delphi.NE ...
- 动作手游实时PVP帧同步方案(客户端)
1.概述 1.1.基于UDP的帧同步方案 在技术选型方面,之所以选择帧同步方案,在Kevin的一篇介绍PVP帧同步后台实现的文章中已经做了详细叙述,这里简单摘要如下: 高一致性.如果每一帧的输入都同步 ...
- three.js模型
Three.js有一系列导入外部文件的辅助函数,是在three.js之外的,使用前需要额外下载, 在https://github.com/mrdoob/three.js/tree/master/exa ...
- 每天一个linux命令--定时启动
1.设置启动的时间,输入crontab -e命令 设置一种编辑器,进入编辑界面,设置启动的时间为每5分钟启动一次wanghy.sh脚本 # m h dom mon dow command # */ * ...