1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.examples.coap;
21
22 import java.io.IOException;
23 import java.net.InetSocketAddress;
24 import java.net.SocketAddress;
25 import java.nio.ByteBuffer;
26 import java.nio.channels.DatagramChannel;
27 import java.util.Random;
28
29 import org.apache.mina.coap.CoapCode;
30 import org.apache.mina.coap.CoapMessage;
31 import org.apache.mina.coap.CoapOption;
32 import org.apache.mina.coap.CoapOptionType;
33 import org.apache.mina.coap.MessageType;
34 import org.apache.mina.coap.codec.CoapDecoder;
35 import org.apache.mina.coap.codec.CoapEncoder;
36
37 public class BlockingGetClient {
38
39 public static void main(String[] args) {
40 try {
41 DatagramChannel channel = DatagramChannel.open();
42
43 InetSocketAddress target = new InetSocketAddress("127.0.0.1", 5683);
44
45 channel.connect(target);
46
47 System.err.println(channel);
48
49 CoapEncoder encoder = new CoapEncoder();
50 CoapDecoder decoder = new CoapDecoder();
51 ByteBuffer buff = ByteBuffer.allocateDirect(2048);
52
53 Random r = new Random();
54 byte[] url = "nlp".getBytes();
55 CoapMessage msg = new CoapMessage(1, MessageType.CONFIRMABLE, CoapCode.GET.getCode(), 1234, null,
56 new CoapOption[] { new CoapOption(CoapOptionType.URI_PATH, url) }, null);
57
58 for (int j = 0; j < 8; j++) {
59 long start = System.currentTimeMillis();
60 final int count = 100000;
61 for (int i = 0; i < count; i++) {
62 buff.position(0);
63 buff.limit(buff.capacity());
64 int id = r.nextInt(1024);
65 msg.setId(id);
66 int bytes = channel.send(encoder.encode(msg, null), target);
67
68 if (bytes < 1) {
69 System.err.println("write fail :/ " + bytes);
70 } else {
71 buff.position(0);
72 buff.limit(buff.capacity());
73 SocketAddress addy = channel.receive(buff);
74 buff.flip();
75 CoapMessage response = decoder.decode(buff, null);
76 if (response.getId() != id) {
77 System.err.println("gni?");
78 }
79
80 }
81 }
82 System.err.println("time : " + (System.currentTimeMillis() - start) + "ms");
83 }
84
85 } catch (IOException e) {
86 e.printStackTrace();
87 }
88 }
89 }