view rep/channel/SelectionKeySimulator.java @ 210:3e0cd34d625d

*** empty log message ***
author kent
date Sat, 30 Aug 2008 14:35:53 +0900
parents dfc2afab1325
children 6cd4aab9fea3
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;

public class SelectionKeySimulator<P> extends REPSelectionKey<P>{
	
	private int interestOpt;
	private SelectableChannel channel;
	private int ready;
	public Selector selector;

	public SelectionKeySimulator(SelectableChannel cs, int opt, Selector _selector) {
		super(null);
		channel = cs;
		interestOpt = opt;
		selector = _selector;
	}
	public SelectionKeySimulator(SelectionKey k) {
		super(null);
		channel = k.channel();
		interestOpt = k.interestOps();
		selector = k.selector();
	}


	public boolean isAble() {
		if ( (interestOpt&OP_READ)!=0 && isReadable() )
			return true;
		else if( (interestOpt&OP_ACCEPT)!=0 && isAcceptable() )
			return true;
		else if( (interestOpt&OP_WRITE)!=0 && isWritable() )
			return true;
		else
			return false;
	}

	public void setFlag() {
		SelectableChannelSimulator<?> scs = (SelectableChannelSimulator<?>) channel;
		ready = 0;
		if(scs.isAcceptable()) ready |= OP_ACCEPT;
		if(scs.isReadable()) ready |= OP_READ;
		if(scs.isWritable()) ready |= OP_WRITE;
	}

	public SelectableChannel channel() {
		return channel;
	}

	public SelectableChannel channel(REPPack<P> packer) {
		return channel;
	}

	@SuppressWarnings("unchecked")
	public REPSocketChannel<P> accept(REPPack<P> pack) throws IOException {
		assert(channel instanceof ServerChannelSimulator);
		ServerChannelSimulator<P> scs = (ServerChannelSimulator<P>) channel;
		return scs.accept1();
	}

	@Override
	public void cancel() {
		System.err.println("cancel is not implemented yet.");
		//selector.
	}

	@Override
	public int interestOps() {
		return interestOpt;
	}

	@Override
	public SelectionKey interestOps(int ops) {
		interestOpt = ops;
		return this;
	}

	@Override
	public boolean isValid() {
		return true;
	}


	@Override
	public Selector selector() {
		return selector;
	}

	@Override
	public int readyOps() {
		int ops=0;
		//if ( channel instanceof SelectableChannelSimulator){
		if ( channel instanceof ServerChannelSimulator ){
			ServerChannelSimulator<?> scs = (ServerChannelSimulator<?>) channel;
			ops = ( OP_ACCEPT * (scs.isAcceptable()? 1:0) );
		}
		if ( channel instanceof ChannelSimulator ){
			ChannelSimulator<?> scs = (ChannelSimulator<?>) channel;
			ops = ( OP_READ * (scs.isReadable()? 1:0) )
					| ( OP_WRITE * (scs.isWritable()? 1:0) );
			// (OP_READ & true) がつかえないらしい.
		}
		return ops;
	}

}