public static void main(String[] args) {
final Map<String, IoSession> registration = new ConcurrentHashMap<>();
// create a CoAP resource registry
final ResourceRegistry reg = new ResourceRegistry();
reg.register(new AbstractResourceHandler() {
@Override
public String getPath() {
return "demo";
}
@Override
public CoapResponse handle(CoapMessage request, IoSession session) {
return new CoapResponse(CoapCode.CONTENT.getCode(), "niah niah niah niah niah\n niah niah niah\n"
.getBytes(), new CoapOption(CoapOptionType.CONTENT_FORMAT, new byte[] { 0 }));
}
@Override
public String getTittle() {
return "Some demo resource";
}
});
reg.register(new AbstractResourceHandler() {
@Override
public CoapResponse handle(CoapMessage request, IoSession session) {
String device = null;
try {
for (CoapOption o : request.getOptions()) {
if (o.getType() == CoapOptionType.URI_QUERY) {
String qr = new String(o.getData(), "UTF-8");
if (qr.startsWith("id=")) {
device = qr.substring(2);
}
}
}
if (device != null) {
registration.put(device, session);
return new CoapResponse(CoapCode.CREATED.getCode(), null);
} else {
return new CoapResponse(CoapCode.BAD_REQUEST.getCode(), "no id=xxx parameter".getBytes("UTF-8"));
}
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("no UTF-8 in the JVM", e);
}
}
@Override
public String getPath() {
return "register";
}
});
BioUdpServer server = new BioUdpServer();
final RequestFilter<CoapMessage, CoapMessage> rq = new RequestFilter<>();
server.setFilters(new ProtocolCodecFilter<CoapMessage, ByteBuffer, Void, Void>(
new CoapEncoder(), new CoapDecoder()), rq);
// idle in 10 minute
server.getSessionConfig().setIdleTimeInMillis(IdleStatus.READ_IDLE, 60 * 10_000);
server.setIoHandler(new AbstractIoHandler() {
long start = System.currentTimeMillis();
int count = 0;
@Override
public void messageReceived(IoSession session, Object message) {
System.err.println("rcv : " + message);
CoapMessage resp = reg.respond((CoapMessage) message, session);
System.err.println("resp : " + resp);
session.write(resp);
count++;
if (count >= 100_000) {
System.err.println("time for 100k msg : " + (System.currentTimeMillis() - start));