哪有什么天生如此,只是我们天天坚持。 -Zhiyuan
以前我已经总结了CoAP协议的基础理论知识。没看过的朋友可以出门左转看我的文章
关于CoAP 协议有很多开源代码实现:大家可以参考我的文章选择自己最适合的:
https://segmentfault.com/a/11...
Californium
Let's go!
引入Californium开源框架的依赖californium-core
启动服务端:
public static void main(String[] args) {
// 创建服务端
CoapServer server = new CoapServer();
// 启动服务端
server.start();
}
让我们从CoapServer这个类开始,对整个框架进行分析。首先让我们看看构造方法CoapServer()里面做了什么:
public CoapServer(final NetworkConfig config, final int... ports) {
// 初始化配置
if (config != null) {
this.config = config;
} else {
this.config = NetworkConfig.getStandard();
}
// 初始化Resource
this.root = createRoot();
// 初始化MessageDeliverer
this.deliverer = new ServerMessageDeliverer(root);
CoapResource wellKnown = new CoapResource(".well-known");
wellKnown.setVisible(false);
wellKnown.add(new DiscoveryResource(root));
root.add(wellKnown);
// 初始化EndPoints
this.endpoints = new ArrayList<>();
// 初始化线程池
this.executor = Executors.newScheduledThreadPool(this.config.getInt(NetworkConfig.Keys.PROTOCOL_STAGE_THREAD_COUNT), new NamedThreadFactory("CoapServer#"));
// 添加Endpoint
for (int port : ports) {
addEndpoint(new CoapEndpoint(port, this.config));
}
}
构造方法初始化了一些成员变量。其中,Endpoint负责与网络进行通信,MessageDeliverer负责分发请求,Resource负责处理请求。接着让我们看看启动方法start()又做了哪些事:
public void start() {
// 如果没有一个Endpoint与CoapServer进行绑定,那就创建一个默认的Endpoint
...
// 一个一个地将Endpoint启动
int started = 0;
for (Endpoint ep:endpoints) {
try {
ep.start();
++started;
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Cannot start server endpoint [" + ep.getAddress() + "]", e);
}
}
if (started==0) {
throw new IllegalStateException("None of the server endpoints could be started");
}
}
启动方法很简单,主要是将所有的Endpoint一个个启动。至此,服务端算是启动成功了。让我们稍微总结一下几个类的关系
如上图,消息会