view src/pathfinder/mergetest/SeMaSimulator.java @ 153:6326e5ea4595

*** empty log message ***
author pin
date Sat, 23 Aug 2008 11:28:16 +0900
parents 5942e0e3c632
children
line wrap: on
line source

package pathfinder.mergetest;

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

import remoteeditor.command.REPCommand;

public class SeMaSimulator<P extends REPCommand> extends Thread {
	protected int MAX_PACKET;
	protected int MAX_CLIENT;
	protected boolean running=true;
	protected NetworkSimulator<P> ns;
	protected List<ChannelSimulator<P>> csList;

	public SeMaSimulator(NetworkSimulator<P> _ns, int max_client, int max_packet){
		ns = _ns;
		MAX_CLIENT = max_client;
		MAX_PACKET = max_packet;
		csList = new ArrayList<ChannelSimulator<P>>();
	}
	public SeMaSimulator(NetworkSimulator<P> _ns, int max_client){
		this(_ns, max_client, 0);
	}
	public SeMaSimulator(NetworkSimulator<P> _ns){
		this(_ns, 2);
	}

	synchronized public void finish(){
		synchronized(ns){
			running = false;
			ns.notify();
		}
	}

	/**
	 * Check whether the NetworkSimulator hold waiting connections.
	 */
	protected void checkAccept(){
		ChannelSimulator<P> cs;
		while((cs=ns.accept())!=null){
			csList.add(cs);
		}
	}
	public void init(){
		ns.writeLog("SessionManager.init", 1);
		while(csList.size()<MAX_CLIENT){ checkAccept(); Thread.yield(); }
	}

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

		ns.writeLog("SessionManager start.", 1);

		/* Main Loop */
		ChannelSimulator<P> cs = csList.get(i);
		while(running
				&& (MAX_PACKET==0 || count<MAX_PACKET)){
			synchronized(ns){
				int prev_i=i;
				while((packet=cs.poll())==null && running){
					i = (i+1)%csList.size();   // i++
					cs = csList.get(i);        // 次のChennelをゲット
					if(i==prev_i) try { ns.wait(); } catch (InterruptedException e) { e.printStackTrace(); }
				}
			}
			if(!running) break;

			ns.writeLog("SeMa pass packet to "+i+":>> "+packet.toString(), 3);
			i = (i+1)%csList.size();   // i++
			cs = csList.get(i);        // 次のChennelをゲット

			if ( !cs.write(packet) ){
				ns.writeLog("Session Manager failed to write.", 0);
			}
			count++;
		}
		ns.writeLog("SessionManager finish.", 1);
	}
}