以下分析libcoap client.c,客户端请求
使用客户端命令进行请求,反馈如下
$ ./coap-client -m get coap://127.0.0.1/
$./ coap-client -m get coap://127.0.0.1/.well-known/core
coap-client 参数类型及说明
-A type 设置期望获取的媒体类型
-t type 设置请求媒体类型
-b num 设置分块大小
-B seconds 设置等待响应超时时间
-e text 设置请求数据类型
-f file 指定GET或 POST的数据文件
-m method 请求方法,get,post
-N 发送NON请求
-o file 响应数据写入到文件中
-p port 监听端口
-s duartion 启用观察者模式,并设置间隔时间
-v num 设置debug等级
-T token 用户自定义token
-k key 设置用户预分享的秘钥
-u user 设置用户标识符。
在server.c的init_resources函数中新增新的URI-hello,和属性world
r = coap_resource_init((unsigned char *)"hello", 5, 0);
coap_register_handler(r, COAP_REQUEST_GET, hnd_get_hello);
coap_add_attr(r, (unsigned char *)"world", 5, (unsigned char *)"0", 1, 0);
coap_add_resource(ctx, r);
增加操作调用函数hnd_get_hello
,
#define HELLO "Hello world!\n"
void
hnd_get_hello(coap_context_t *ctx, struct coap_resource_t *resource,
coap_address_t *peer, coap_pdu_t *request, str *token,
coap_pdu_t *response){
unsigned char buf[3];
response->hdr->code = COAP_RESPONSE_CODE(205);
coap_add_option(response, COAP_OPTION_CONTENT_TYPE,
coap_encode_var_bytes(buf, COAP_MEDIATYPE_TEXT_PLAIN), buf);
coap_add_option(response, COAP_OPTION_MAXAGE,
coap_encode_var_bytes(buf, 0x2ffff) ,buf);
coap_add_data(response, strlen(HELLO), (unsigned char *)HELLO);
}
执行新的URI
$./coap-client -m get coap://127.0.0.1/hello