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