view src/pathfinder/SeMaEmulator.java @ 70:9c19d6d61a03

refactor
author kent
date Thu, 08 Nov 2007 15:11:13 +0900
parents 3c9b8371681d
children d44d734502da
line wrap: on
line source

package pathfinder;

import java.util.ArrayList;
import java.util.List;

public class SeMaEmulator<P> extends Thread {
	private NetworkSimulator<P> ns;
	private List<ChannelSimulator<P>> csList;

	public SeMaEmulator(NetworkSimulator<P> _ns){
		ns = _ns;
		csList = new ArrayList<ChannelSimulator<P>>();
	}

	/**
	 * Check whether NetworkSimulator hold waiting connections.
	 */
	private boolean checkAccept(){
		ChannelSimulator<P> cs;
		cs = ns.accept();
		if (cs==null) return false;
		csList.add(cs);
		return true;
	}
	public void waitClient(){
		while(csList.size()<2){
			checkAccept();
		}
	}

	public void run(){
		int i=0;
		P packet;

		waitClient();
		System.out.println("SessionManager was initialized.");
		
		/* Main Loop */
		ChannelSimulator<P> cs = csList.get(i);
		while(true){
			packet=cs.read();                    // [i]からread
			i = (i+1)%csList.size();             // i++
			cs = csList.get(i);                  // 次のChennelをゲット
			if (packet!=null) cs.write(packet);  // readできていたならそれを書き込む
			if (i==0) checkAccept();             //全部回ったらaccept待ちをチェック
		}
	}
}