server.c中
从网络端来看,还是一个基于UDP的网络程序
- 创建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);