深入了解物联网协议CoAP的核心和网络部分

目录

前言

一、Coap的Core包

1、Coap对象

2、Message对象

3、Request对象

4、Response对象

二、Coap的NetWork调试

1、UDP运行模式

 2、Network消息接收

3、Sender线程发送数据 

三、总结


前言

        在之前的博文中,对Californium中Coap的实现进行了简要的介绍,分别从Server和Client两端进行了基础介绍。对于面向连接的连接协议,一定是离不开网络层。本次将重点介绍Coap的Core核心实现以及网络层定义,虽然在Californium协议中,已经全面的实现了Coap协议。

        本文将以Core包和NetWork包为主线,对Coap协议中,关于Californium框架的具体实现方式和代码编写进行讲解,希望对想了解Coap的实现朋友对其有更深入的了解。

一、Coap的Core包

        Coap的核心包定义了Coap适配的协议,请求协议头、响应对象等。主要包含Coap、Message、Option、Request、Response等几个对象。

1、Coap对象

        首先来看一下Coap对象的类图,如下图所示:

         从上图可以看出,Coap类主要是一个常量类,其中包含了消息类型、请求类型编码、响应码、消息格式类型等。请注意这里是采用枚举属性的方式进行定义。比如消息类型的定义,部分代码已精简:

/**
	 * CoAP defines four types of messages:
	 * Confirmable, Non-confirmable, Acknowledgment, Reset.
	 */
	public enum Type {

		/** The Confirmable. */
		CON(0),

		/** The Non-confirmable. */
		NON(1),

		/** The Acknowledgment. */
		ACK(2),

		/** The Reject. */
		RST(3);

		/** The integer value of a message type. */
		public final int value;
	}

以上四种消息类型表示如下:

序号 类型 说明
1 CON 需要被确认的请求,如果CON请求被发送,那么对方必须做出响应。这有点像TCP,对方必须给确认收到消息,用以可靠消息传输。
2 NON 不需要被确认的请求,如果NON请求被发送,那么对方不必做出回应。这适用于消息会重复频繁的发送,丢包不影响正常操作。这个和UDP很像。用以不可靠消息传输。
3 ACK  应答消息,对应的是CON消息的应答。
4 RST 复位消息,可靠传输时候接收的消息不认识或错误时,不能回ACK消息,必须回RST消息。

        请求方法枚举,这里主要定义了Coap请求方法编码,比如GET、POST、PUT等。关键代码如下:

/**
	 * The enumeration of request codes: GET, POST, PUT and DELETE.
	 */
	public enum Code {

		/** The GET code. */
		GET(1),

		/** The POST code. */
		POST(2),

		/** The PUT code. */
		PUT(3),

		/** The DELETE code. */
		DELETE(4);

		/** The code value. */
		public final int value;
	}

2、Message对象

        在通讯建立后,依赖于网络传输对象,Server端和Client端都会进行消息的传递。这是实际数据传递时所依赖的对象。这里重点介绍Message对象,大家可以重点查看Californium的源码来着重了解。首先来看一下Message对象的类图。

         在message对象中,定义了消息类型、mid、token、payload等信息。

消息头(HEAD)

第一行是消息头,必须有,固定4个byte。Ver : 2bit, 版本信息,当前是必须写0x01。T: 2bit, 消息类型,包括 CON, NON. ACK, RST这4种。TKL: 4bit,token长度, 当前支持0~8B长度,其他长度保留将来扩展用。

Code:8bit,分成前3bit(0~7)和后5bit(0~31),前3bit代表类型。 0代表空消息或者请求码, 2开头代表响应码,取值如下:

1 0.00 Indicates an Empty message

2 0.01-0.31 Indicates a request.

3 1.00-1.31 Reserved

4 2.00-5.31 Indicates a response.

5 6.00-7.31 Reserved

Message ID:16bit, 代表消息MID,每个消息都有一个ID ,重发的消息MID不变。token(可选)用于将响应与请求匹配。 token值为0到8字节的序列。 ( 每条消息必须带有一个标记, 即使它的长度为零)。 每个请求都带有一个客户端生成的token, 服务器在任何结果响应中都必须对其进行回应。token类似消息ID,用以标记消息的唯一性。token还是消息安全性的一个设置,使用全8字节的随机数,使伪造的报文无法获得验证通过。

option

请求消息与回应消息都可以0~多个options。 主要用于描述请求或者响应对应的各个属性,类似参数或者特征描述,比如是否用到代理服务器,目的主机的端口等。

payload

实际携带数据内容,若有,前面加payload标识符“0xFF”,如果没有payload标识符,那么就代表这是一个0长度的payload。如果存在payload标识符但其后跟随的是0长度的payload,那么必须当作消息格式错误处理。

/** The Constant NONE in case no MID has been set. */
	public static final int NONE = -1;
	/**
	 * The largest message ID allowed by CoAP.
	 * <p>
	 * The value of this constant is 2^16 - 1.
	 */
	public static final int MAX_MID = (1 << 16) - 1;

	/** The type. One of {CON, NON, ACK or RST}. */
	private CoAP.Type type;

	/** The 16-bit Message Identification. */
	private volatile int mid = NONE; // Message ID

	/**
	 * The token, a 0-8 byte array.
	 * <p>
	 * This field is initialized to {@code null} so that client code can
	 * determine whether the message already has a token assigned or not. An
	 * empty array would not work here because it is already a valid token
	 * according to the CoAP spec.
	 */
	private volatile Token token = null;

	/** The set of options of this message. */
	private OptionSet options;

	/** The payload of this message. */
	private byte[] payload;

	/**
	 * Destination endpoint context. Used for outgoing messages.
	 */
	private volatile EndpointContext destinationContext;

	/**
	 * Source endpoint context. Used for incoming messages.
	 */
	private volatile EndpointContext sourceContext;

	/** Indicates if the message has sent. */
	private volatile boolean sent;

	/** Indicates if the message has been acknowledged. */
	private volatile boolean acknowledged;

	/** Indicates if the message has been rejected. */
	private volatile boolean rejected;

	/** Indicates if the message has been canceled. */
	private volatile boolean canceled;

	/** Indicates if the message has timed out */
	private volatile boolean timedOut; // Important for CONs

	/** Indicates if the message is a duplicate. */
	private volatile boolean duplicate;

	/** Indicates if sending the message caused an error. */
	private volatile Throwable sendError;

	/** The serialized message as byte array. */
	private volatile byte[] bytes;

3、Request对象

        与Http协议类似,Coap中,伴随着每一次的请求发送,势必也会有一个request对象。在request中进行信息的传递。因此,Requet也是继承自Message,其类图如下:

        可以看到,在Reques对象中,针对Get、Put、Post、Delete等不同的方法也进行了定义。

/**
	 * Convenience factory method to construct a POST request and equivalent to
	 * <code>new Request(Code.POST);</code>
	 * 
	 * @return a new POST request
	 */
	public static Request newPost() {
		return new Request(Code.POST);
	}

	/**
	 * Convenience factory method to construct a PUT request and equivalent to
	 * <code>new Request(Code.PUT);</code>
	 * 
	 * @return a new PUT request
	 */
	public static Request newPut() {
		return new Request(Code.PUT);
	}

	/**
	 * Convenience factory method to construct a DELETE request and equivalent
	 * to <code>new Request(Code.DELETE);</code>
	 * 
	 * @return a new DELETE request
	 */
	public static Request newDelete() {
		return new Request(Code.DELETE);
	}

4、Response对象

        response对象与http也是类似的,跟B/S模式是一样的。有Client的请求对象,一定会对应有Server的Response对象。与Request一样,Response也是Message类的子类。

         Reponse的方法相对比较简单,主要是将相应的信息放置到响应对象中,然后返回给前端。其主要的方法如下:

/**
	 * Creates a response to the provided received request with the specified
	 * response code. The destination endpoint context of the response will be
	 * the source endpoint context of the request. Type and MID are usually set
	 * automatically by the {@link ReliabilityLayer}. The token is set
	 * automatically by the {@link Matcher}.
	 *
	 * @param receivedRequest the request
	 * @param code the code
	 * @return the response
	 * @throws IllegalArgumentException if request has no source endpoint
	 *             context.
	 */
	public static Response createResponse(Request receivedRequest, ResponseCode code) {
		if (receivedRequest.getSourceContext() == null) {
			throw new IllegalArgumentException("received request must contain a source context.");
		}
		Response response = new Response(code);
		response.setDestinationContext(receivedRequest.getSourceContext());
		return response;
	}

        由于篇幅有限,关于Core包的相关类介绍先到此,感兴趣的朋友可以下载源码后自己研究,以上将core包中比较重要的四个类进行讲解。下一步在讲解消息构造和方法运行时会更一步的涉及到这些类。因此着重介绍一下,以免不了解的读者不清楚具体的定义。

二、Coap的NetWork调试

        关于Coap的NetWork中的使用,准备结合动态运行过程进行讲解,主要结合Debug的方式,以类图这种分析方法不能完全的展示其调用过程和初始化步骤。比如,为什么说Coap默认是运行在UDP协议之下的,在系统运行时,其协议转换又是怎么工作的。下面将揭开这个面纱。

1、UDP运行模式

        众所周知,Coap默认试运行在UCP协议下的,我们来看一下其具体的定义。在CoapServer中创建CoapEndpoint时,可以看到以下的设置过程。

 在CoapEndpoint.java 中1285行,很清楚的看到这创建了UDPConnector连接器。

 2、Network消息接收

        在进行以上的对象定义之后,Coap基本就可以依赖于网络进行请求的运行了。启动方法

         在这里,分别定义了发送线程集合和接收线程集合,用来保存接收和发送对象。receiverCount默认是16.

3、Sender线程发送数据 

 在这里可以看到要发送的数据包信息,

4、Receiver接收响应

protected void work() throws IOException {
			datagram.setLength(size);
			socket.receive(datagram);
			LOGGER.debug("UDPConnector ({}) received {} bytes from {}:{}",
					new Object[]{socket.getLocalSocketAddress(), datagram.getLength(),
						datagram.getAddress(), datagram.getPort()});
			byte[] bytes = Arrays.copyOfRange(datagram.getData(), datagram.getOffset(), datagram.getLength());
			RawData msg = RawData.inbound(bytes, new AddressEndpointContext(datagram.getAddress(), datagram.getPort()), false);

			receiver.receiveData(msg);
		}

在work方法中进行信息的转换,获取响应报文。通过转换后就可以获取以下报文体:

2.05
{"Content-Format":"text/plain"}
Hello CoAP!This is from Java coap server

Advanced

==[ CoAP Response ]============================================
MID    : 26037
Token  : [6243fee1521b9e40]
Type   : ACK
Status : 2.05
Options: {"Content-Format":"text/plain"}
RTT    : 43333 ms
Payload: 40 Bytes
---------------------------------------------------------------
Hello CoAP!This is from Java coap server
===============================================================

三、总结

        以上就是本文的主要内容,本文将以Core包和NetWork包为主线,对Coap协议中,关于Californium框架的具体实现方式和代码编写进行讲解,希望对想了解Coap的实现朋友对其有更深入的了解。行文仓促,如有不当之处,请留言批评指正。

物联沃分享整理
物联沃-IOTWORD物联网 » 深入了解物联网协议CoAP的核心和网络部分

发表评论