view test/channeltest/StringPacker.java @ 481:607f1dfe2b80

add comment
author Shinji KONO <kono@ie.u-ryukyu.ac.jp>
date Fri, 15 Oct 2010 19:47:53 +0900
parents 44d502851c9e
children
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.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 どれくらいにしよう?

		if (log.length()==0) return null;
		/* ヘッダ あとでもう一回書き直す */
		blog.putInt(0);
		
		/* 文字列を追加  */
		for(int i=0; i<log.length(); i++){
			blog.putChar(log.charAt(i));
		}
		blog.limit(blog.position());

		/* ヘッダに書き込む情報  */
		size = blog.position();
		blog.rewind();
		/* ヘッダ 文字列の長さ */
		blog.putInt(size-4);
		blog.rewind();

		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();
		
		if(size==0) return null;

		// Stringの読み込み 
		bb = ByteBuffer.allocate(size*2);
		bb.limit(size);
		while(bb.remaining()>0)
			sc.read(bb);

		//  Stringに変換して返す
		bb.rewind();
		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<String> 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();
		}
	}
}