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