我愿意使用CoAP协议来实现基于java推送的消息传递系统。特别是在这样的系统中,客户端仅在与服务器(资源)的连接打开一次,并且服务器以特定速率(例如,每秒10个消息)推送消息(“不可确认”)。但是我没有找到任何现有的解决方案来构建上述系统。
我发现基于拉取的消息传递系统。对于这种情况,客户端打开与服务器的连接,并在一段时间后客户端发送GET请求。然后,服务器处理请求并将单个消息推送(作为响应)到客户端。
因此,对于每个GET,我有一条消息作为响应 - 即双向异步交互。
有没有人知道如何使用CoAP实现基于推送的消息传递系统? CoAP是否支持这样的系统?
基于拉取的消息传递系统实现如下
服务器部件
public class CoapServerPartAsync extends CoapServer {
private static final int COAP_PORT = 8891;
private static int incrementor = 1;
/*
* Application entry point.
*/
public static void main(String[] args) {
try {
// create server
CoapServerPartAsync server = new CoapServerPartAsync();
// add endpoints on all IP addresses
server.addEndpoints();
server.start();
} catch (SocketException e) {
System.err.println("Failed to initialize server: " + e.getMessage());
}
}
/**
* Add endpoints listening on default CoAP port on all IP addresses of all network interfaces.
*
* @throws SocketException if network interfaces cannot be determined
*/
private void addEndpoints() throws SocketException {
InetSocketAddress bindToAddress = new InetSocketAddress("127.0.0.1", COAP_PORT);
addEndpoint(new CoapEndpoint(bindToAddress));
}
/*
* Constructor for a new Hello-World server. Here, the resources
* of the server are initialized.
*/
public CoapServerPartAsync() throws SocketException {
// provide an instance of a Hello-World resource
add(new HelloWorldResource());
}
/*
* Definition of the Hello-World Resource
*/
class HelloWorldResource extends CoapResource {
public HelloWorldResource() {
// set resource identifier
super("helloWorld");
// set display name
getAttributes().setTitle("Hello-World Resource");
}
@Override
public void handleGET(CoapExchange exchange){
// respond to the request
System.out.println("Push [Hello World!"+(incrementor)+"]");
exchange.respond("Hello World!"+(incrementor));
incrementor++;
}
}
}
客户端部分
public class CoapClientPartAsync {
// static boolean getResponse = false;
public static void main(String args[]) {
CoapClient client = new CoapClient("coap://127.0.0.1:8891/helloWorld").useNONs();
while(true){
CoapObserveRelation relation = client.observe(
new CoapHandler() {
@Override public void onLoad(CoapResponse response){
String content = response.getResponseText();
System.out.println("NOTIFICATION: " + content);
}
@Override public void onError() {
System.err.println("OBSERVING FAILED (press enter to exit)");
}
});
try {
Thread.sleep(1000);
}catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}