view test/channeltest/testSeMa.java @ 308:c5be84d53c7f channel-simulator-update **INVALID**

*** empty log message ***
author kono
date Sat, 04 Oct 2008 22:12:34 +0900
parents d6a33e295d47
children
line wrap: on
line source

package test.channeltest;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.SelectionKey;
import java.util.LinkedList;
import java.util.Set;

import rep.channel.REPLogger;
import rep.channel.REPPack;
import rep.channel.REPSelectionKey;
import rep.channel.REPSelector;
import rep.channel.REPServerSocketChannel;
import rep.channel.REPSocketChannel;

public class testSeMa extends Thread{

	SocketAddress IP;
	boolean running=true;
	REPLogger ns;
	LinkedList<REPSocketChannel<String>> channels;

	public testSeMa(String name, String host, int port){
		super(name);
		IP = new InetSocketAddress(host,port);
		ns = REPLogger.singleton();
		channels = new LinkedList<REPSocketChannel<String>>();
	}
	public void init(){

	}

	public void run() {
		REPSelector<String> selector=null;

		REPServerSocketChannel<String> scs;
		REPPack<String> pack = new StringPacker();
		try {
			selector = REPSelector.<String>create();
			scs = REPServerSocketChannel.<String>open(pack);
			scs.socket().setReuseAddress(true);
			scs.socket().bind(IP);
			scs.configureBlocking(false);
			scs.register(selector, SelectionKey.OP_ACCEPT, null);
		} catch (IOException e1) {
			e1.printStackTrace();
			ns.writeLog("cannot create REPServerSocketChannel!, exit.");
			return;
		}
		ns.writeLog("selector is "+selector.toString());
		ns.writeLog("REPssc is "+scs.toString());

		ns.writeLog("SessionManager starts main routine.", 1);

		/* Main Loop */
		while(running){

			try { 
				selector.select(); 
				Set<REPSelectionKey<String>> set = selector.selectedKeys1();
				for(REPSelectionKey<String> key : set) {

					if(key.isAcceptable()){
						REPSocketChannel<String> channel = key.accept(pack);
						if(channel==null) continue;
						channel.configureBlocking(false);
						channel.register(selector, SelectionKey.OP_READ, null);
						ns.writeLog("accepts a client.", 1);

					}else if(key.isReadable()){
						try {
							REPSocketChannel<String> channel = key.channel1();
							String packet;
							packet = channel.read();
							if (packet==null) continue;
							ns.writeLog("receives String==> `"+packet+"\'", 1);
							channel.write(this.getName()+": get `"+packet+"\'");
						}catch (IOException e) { 
							ns.writeLog("channel "+ns+"closed.");
							key.cancel();
						}
					}
				}
			}
			catch (IOException e) { e.printStackTrace();}
		}

	}
}