libcoap的使用和CoAP協議分析二

以下分析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  

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章