libcoap(一)

server.c中

从网络端来看,还是一个基于UDP的网络程序

  1. 创建socket
ctx = get_context(addr_str, port_str);
  if (!ctx)
    return -1;
ctx = coap_new_context(&addr);
c->sockfd = socket(listen_addr->addr.sa.sa_family, SOCK_DGRAM, 0);
if ( setsockopt( c->sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse) ) < 0 ) {
#ifndef NDEBUG
    coap_log(LOG_WARNING, "setsockopt SO_REUSEADDR\n");
#endif
  }

2.绑定本机IP

if (bind(c->sockfd, &listen_addr->addr.sa, listen_addr->size) < 0) {
#ifndef NDEBUG
    coap_log(LOG_EMERG, "coap_new_context: bind\n");
#endif
    goto onerror;
  }

3.检测有没有socket到来

 result = select( FD_SETSIZE, &readfds, 0, 0, timeout );

4.接收数据

coap_read( ctx );   /* read received data */
bytes_read = recvfrom(ctx->sockfd, buf, sizeof(buf), 0,
            &src.addr.sa, &src.size);

5.返回数据

coap_dispatch( ctx );   /* and dispatch PDUs from receivequeue */
      if (coap_send(context, &rcvd->remote, response) 
          == COAP_INVALID_TID) {
        warn("coap_dispatch: error sending reponse\n");
      }
coap_tid_t 
coap_send(coap_context_t *context, 
      const coap_address_t *dst, 
      coap_pdu_t *pdu) {
  return coap_send_impl(context, dst, pdu);
}
  bytes_written = sendto( context->sockfd, pdu->hdr, pdu->length, 0,
              &dst->addr.sa, dst->size);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值