view rep/channel/SelectorSimulator.java @ 203:4c0a94836357 simullator-nio-both-worked

*** empty log message ***
author kono
date Sat, 30 Aug 2008 11:21:43 +0900
parents 8d7c74610b05
children 0607cc699ba3
line wrap: on
line source

package rep.channel;

import java.io.IOException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.spi.SelectorProvider;
import java.util.HashSet;
import java.util.Set;

public class SelectorSimulator<P> extends REPSelector<P>{
	
	private Set<SelectionKey> keyList;
	private Set<SelectionKey> selectedKeys;
	
	public SelectorSimulator() {
		super(null);
		keyList = new HashSet<SelectionKey>();
	}

	public int select() throws IOException {
		selectedKeys = new HashSet<SelectionKey>();
		
		synchronized(this) {

			while(selectedKeys.isEmpty()){
				for(SelectionKey key : keyList){
					if(((SelectionKeySimulator<?>) key).isAble())
						selectedKeys.add(key);
				}

				if(selectedKeys.isEmpty())
					try {
						this.wait();
					} catch (InterruptedException e) {
						throw new IOException("Error, Selector was interrupted!");
					}
			}
		}
		return selectedKeys.size();
	}

	public SelectionKeySimulator<P> register(SelectableChannel cs, int opt){
		return register(cs, opt, null);
	}
	public SelectionKeySimulator<P> register(SelectableChannel cs, int opt, Object handler){
		SelectionKeySimulator<P> key = new SelectionKeySimulator<P>(cs, opt, this);
		key.attach(handler);
		keyList.add(key);
		return key;
	}
	

	public Set<REPSelectionKey<P>> selectedKeys1() {
			Set<SelectionKey> keys = keyList;
			Set<REPSelectionKey<P>> newKeys = new HashSet<REPSelectionKey<P>>();
			for(SelectionKey k: keys) {
				// REPSelectionKeyを生成しないように注意
				newKeys.add(new SelectionKeySimulator<P>(k));
			}
			return newKeys;//(Set<REPSelectionKey<P>>)newKeys;
	}
	
	public <T> SelectionKey getKey(ChannelSimulator<T> channel){
		for(SelectionKey key : keyList){
			if(key.channel() == channel)
				return key;
		}
		return null;
	}

	@Override
	public void close() throws IOException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean isOpen() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Set<SelectionKey> keys() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public SelectorProvider provider() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int select(long timeout) throws IOException {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int selectNow() throws IOException {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public Selector wakeup() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Set<SelectionKey> selectedKeys() {
		// TODO Auto-generated method stub
		return (Set<SelectionKey>)selectedKeys;
	}

}