前面说过一次通信的数据包分两次发送,第一个存储实际数据的大小,第二个存储实际的数据。
事实上,为了方便服务端客户端更好地对收到的数据进行处理,发送的实际的数据本身也有一定的格式。
请求
searpc-named-pipe-transport.c
static char *
request_to_json (const char *service, const char *fcall_str, size_t fcall_len)
{
json_t *object = json_object ();
char *temp_request = g_malloc0(fcall_len + 1);
memcpy(temp_request, fcall_str, fcall_len);
json_object_set_string_member (object, "service", service);
json_object_set_string_member (object, "request", temp_request);
g_free (temp_request);
char *str = json_dumps (object, 0);
json_decref (object);
return str;
}
static int
request_from_json (const char *content, size_t len, char **service, char **fcall_str)
{
json_error_t jerror;
json_t *object = json_loadb(content, len, 0, &jerror);
if (!object) {
g_warning ("Failed to parse request body: %s.\n", strlen(jerror.text) > 0 ? jerror.text : "");
return -1;
}
*service = g_strdup(json_object_get_string_member (object, "service"));
*fcall_str = g_strdup(json_object_get_string_member(object, "request"));
json_decref (object);
if (!*service || !*fcall_str) {
g_free (*service);
g_free (*fcall_str);
return -1;
}
return 0;
}
可以看到请求本身的结构为
{
"service": ***,
"request": ***,
}
再将请求转化json
格式进行发送。
回复
seafile
对服务返回的结果也做了统一的格式处理。
searpc-client.c
/*
* Returns -1 if error happens in parsing data or data contains error
* message. In this case, the calling function should simply return
* to up layer.
*
* Returns 0 otherwise, and root is set to the root node, object set
* to the root node's containing object.
*/
static int
handle_ret_common (char *data, size_t len, json_t **object, GError **error)
{
int err_code;
const char *err_msg;
json_error_t jerror;
g_return_val_if_fail (object != 0, -1);
*object=json_loadb(data,len,0,&jerror);
if (*object == NULL) {
setjetoge(&jerror,error);
json_decref (*object);
return -1;
}
if (json_object_get (*object, "err_code")) {
err_code = json_integer_value(json_object_get (*object, "err_code"));
err_msg = json_string_value(json_object_get (*object, "err_msg"));
g_set_error (error, DFT_DOMAIN,
err_code, "%s", err_msg);
json_decref (*object);
return -1;
}
return 0;
}
结构为:
{
"ret": ***,
"err_code": ***,
"err_msg": ***
}
总结
到这里,searpc-named-pipe-trans.h/c
文件和named_pipe.py
文件中涉及到的代码基本也全部覆盖到了,通信的部分也就基本介绍完毕了。