XMLRPC的C++代碼在下載后的ros_comm-noetic-develutilitiesxmlrpcpp路徑下。
還好,整個工程不算太大。XMLRPC分成客戶端和服務(wù)器端兩大部分。
咱們先看客戶端,主要代碼在XmlRpcClient.cpp文件里。
擒賊先擒王,XmlRpcClient.cpp文件中最核心的函數(shù)就是execute,用于執(zhí)行遠程調(diào)用,代碼如下。
// Execute the named procedure on the remote server.
// Params should be an array of the arguments for the method.
// Returns true if the request was sent and a result received (although the result might be a fault).
bool XmlRpcClient::execute(const char* method, XmlRpcValue const& params, XmlRpcValue& result)
{
XmlRpcUtil::log(1, "XmlRpcClient::execute: method %s (_connectionState %s).", method, connectionStateStr(_connectionState));
// This is not a thread-safe operation, if you want to do multithreading, use separate
// clients for each thread. If you want to protect yourself from multiple threads
// accessing the same client, replace this code with a real mutex.
if (_executing)
return false;
_executing = true;
ClearFlagOnExit cf(_executing);
_sendAttempts = 0;
_isFault = false;
if ( ! setupConnection())
return false;
if ( ! generateRequest(method, params))
return false;
result.clear();
double msTime = -1.0; // Process until exit is called
_disp.work(msTime);
if (_connectionState != IDLE || ! parseResponse(result)) {
_header = "";
return false;
}
// close() if server does not supports HTTP1.1
// otherwise, reusing the socket to write leads to a SIGPIPE because
// the remote server could shut down the corresponding socket.
if (_header.find("HTTP/1.1 200 OK", 0, 15) != 0) {
close();
}
XmlRpcUtil::log(1, "XmlRpcClient::execute: method %s completed.", method);
_header = "";
_response = "";
return true;
}
它首先調(diào)用setupConnection()函數(shù)與服務(wù)器端建立連接。
連接成功后,調(diào)用generateRequest()函數(shù)生成發(fā)送請求報文。
XMLRPC請求報文的頭部又交給generateHeader()函數(shù)做了,代碼如下。
// Prepend http headers
std::string XmlRpcClient::generateHeader(size_t length) const
{
std::string header =
"POST " + _uri + " HTTP/1.1rn"
"User-Agent: ";
header += XMLRPC_VERSION;
header += "rnHost: ";
header += _host;
char buff[40];
std::snprintf(buff,40,":%drn", _port);
header += buff;
header += "Content-Type: text/xmlrnContent-length: ";
std::snprintf(buff,40,"%zurnrn", length);
return header + buff;
}
主體部分則先將遠程調(diào)用的方法和參數(shù)變成XML格式,generateRequest()函數(shù)再將頭部和主體組合成完整的報文,如下:
std::string header = generateHeader(body.length());
_request = header + body;
把報文發(fā)給服務(wù)器后,就開始靜靜地等待。
一旦接收到服務(wù)器返回的報文后,就調(diào)用parseResponse函數(shù)解析報文數(shù)據(jù),也就是把XML格式變成純凈的數(shù)據(jù)格式。
我們發(fā)現(xiàn),XMLRPC使用了socket功能實現(xiàn)客戶端和服務(wù)器通信。
我們搜索socket這個單詞,發(fā)現(xiàn)它原始的意思是插座。這非常形象,建立連接實現(xiàn)通信就像把插頭插入插座。
雖說XMLRPC也是ROS的一部分,但它畢竟只是一個基礎(chǔ)功能,我們會用即可,暫時不去探究其實現(xiàn)細節(jié),
-
客戶端
+關(guān)注
關(guān)注
1文章
289瀏覽量
16640 -
服務(wù)端
+關(guān)注
關(guān)注
0文章
66瀏覽量
6978 -
ROS
+關(guān)注
關(guān)注
1文章
276瀏覽量
16942
發(fā)布評論請先 登錄
相關(guān)推薦
評論