171
|
1 package test.channeltest;
|
|
2
|
|
3 import java.io.IOException;
|
187
|
4 import java.net.InetSocketAddress;
|
|
5 import java.net.SocketAddress;
|
171
|
6 import java.nio.ByteBuffer;
|
|
7 import java.nio.CharBuffer;
|
187
|
8 import java.nio.channels.SelectionKey;
|
171
|
9 import java.nio.channels.SocketChannel;
|
|
10
|
|
11 import rep.channel.REPPack;
|
187
|
12 import rep.channel.REPSelector;
|
|
13 import rep.channel.REPServerSocketChannel;
|
171
|
14 import rep.channel.REPSocketChannel;
|
|
15
|
187
|
16 public class StringPacker implements REPPack<String> {
|
|
17
|
|
18 public StringPacker(){
|
|
19 }
|
171
|
20
|
|
21 public ByteBuffer packUConv(String log) {
|
|
22 int size;
|
187
|
23 ByteBuffer blog = ByteBuffer.allocate(log.length()*5); // TODO どれくらいにしよう?
|
171
|
24
|
|
25 /* ヘッダ あとでもう一回書き直す */
|
|
26 blog.putInt(0);
|
|
27
|
|
28 /* 文字列を追加 */
|
|
29 CharBuffer cb = blog.asCharBuffer();
|
|
30 cb.put(log);
|
|
31
|
|
32 /* ヘッダに書き込む情報 */
|
187
|
33 size = cb.asReadOnlyBuffer().position();
|
171
|
34 blog.rewind();
|
|
35 /* ヘッダ 文字列の長さ */
|
|
36 blog.putInt(size);
|
|
37 blog.rewind();
|
|
38
|
|
39 return blog;
|
|
40 /*
|
|
41 for(int i=0;i<log.length();i++) {
|
|
42 blog.putChar(log.charAt(i));
|
|
43 }
|
|
44 blog.flip();
|
|
45 return blog;
|
|
46 */
|
|
47 }
|
|
48
|
|
49 public String unpackUConv(SocketChannel sc) throws IOException {
|
|
50 ByteBuffer bb = ByteBuffer.allocate(10);
|
|
51
|
|
52 // ヘッダの読み込み 4Byteのハズ...?
|
|
53 bb.limit(4);
|
|
54 sc.read(bb);
|
187
|
55 bb.rewind();
|
171
|
56 int size = bb.getInt();
|
|
57
|
|
58 // Stringの読み込み
|
|
59 bb = ByteBuffer.allocate(size*2);
|
|
60 bb.limit(size);
|
|
61 sc.read(bb);
|
|
62
|
|
63 // Stringに変換して返す
|
|
64 return bb.asCharBuffer().toString();
|
|
65 }
|
|
66
|
187
|
67 public static void main(String args[]){
|
|
68 REPServerSocketChannel.isSimulation=false;
|
|
69 String str = "Hello World!";
|
|
70 StringPacker sp = new StringPacker();
|
|
71 SocketAddress IP = new InetSocketAddress("localhost",20000);
|
|
72 try {
|
|
73 REPSelector selector;
|
|
74 REPSocketChannel<String> rscS;
|
|
75 REPSocketChannel<String> rscC;
|
|
76 REPServerSocketChannel<String> rss;
|
|
77
|
|
78 selector = REPSelector.create();
|
|
79 rss = REPServerSocketChannel.<String>open(sp);
|
|
80 rss.socket().setReuseAddress(true);
|
|
81 rss.socket().bind(IP);
|
|
82 rss.configureBlocking(false);
|
|
83 rss.register(selector, SelectionKey.OP_ACCEPT, null);
|
171
|
84
|
187
|
85 rscC = REPSocketChannel.<String>create(sp);
|
|
86 rscC.connect(IP);
|
|
87
|
|
88 rscS = rss.accept1();
|
|
89
|
|
90 rscC.write(str);
|
|
91
|
|
92 System.out.println("receive `"+rscS.read()+"\'");
|
171
|
93
|
187
|
94 } catch (IOException e) {
|
|
95 // TODO Auto-generated catch block
|
|
96 e.printStackTrace();
|
|
97 }
|
|
98 }
|
171
|
99 }
|