Mercurial > hg > RemoteEditor > REPSessionManager
view test/channeltest/StringPacker.java @ 196:b85525d83b46
*** empty log message ***
author | kono |
---|---|
date | Fri, 29 Aug 2008 21:39:13 +0900 |
parents | fc8ee7600cf3 |
children | ffedaf382e0c |
line wrap: on
line source
package test.channeltest; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import rep.channel.REPPack; import rep.channel.REPSelector; import rep.channel.REPServerSocketChannel; import rep.channel.REPSocketChannel; public class StringPacker implements REPPack<String> { public StringPacker(){ } public ByteBuffer packUConv(String log) { int size; ByteBuffer blog = ByteBuffer.allocate(log.length()*5); // TODO どれくらいにしよう? /* ヘッダ あとでもう一回書き直す */ blog.putInt(0); /* 文字列を追加 */ CharBuffer cb = blog.asCharBuffer(); cb.put(log); /* ヘッダに書き込む情報 */ size = cb.asReadOnlyBuffer().position(); blog.rewind(); /* ヘッダ 文字列の長さ */ blog.putInt(size); blog.rewind(); return blog; /* for(int i=0;i<log.length();i++) { blog.putChar(log.charAt(i)); } blog.flip(); return blog; */ } public String unpackUConv(SocketChannel sc) throws IOException { ByteBuffer bb = ByteBuffer.allocate(10); // ヘッダの読み込み 4Byteのハズ...? bb.limit(4); sc.read(bb); bb.rewind(); int size = bb.getInt(); // Stringの読み込み bb = ByteBuffer.allocate(size*2); bb.limit(size); sc.read(bb); // Stringに変換して返す return bb.asCharBuffer().toString(); } public static void main(String args[]){ REPServerSocketChannel.isSimulation=false; String str = "Hello World!"; StringPacker sp = new StringPacker(); SocketAddress IP = new InetSocketAddress("localhost",20000); try { REPSelector selector; REPSocketChannel<String> rscS; REPSocketChannel<String> rscC; REPServerSocketChannel<String> rss; selector = REPSelector.create(); rss = REPServerSocketChannel.<String>open(sp); rss.socket().setReuseAddress(true); rss.socket().bind(IP); rss.configureBlocking(false); rss.register(selector, SelectionKey.OP_ACCEPT, null); rscC = REPSocketChannel.<String>create(sp); rscC.connect(IP); rscS = rss.accept1(); rscC.write(str); System.out.println("receive `"+rscS.read()+"\'"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }