view test/channeltest/testSeMa.java @ 175:5653cf8e3c8b

*** empty log message ***
author kent
date Thu, 28 Aug 2008 21:22:07 +0900
parents 72252e970a8b
children f34608ae1ed2
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 rep.channel.REPLogger;
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(){

	}

	@SuppressWarnings("unchecked")
	public void run() {
		REPSelector selector=null;

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

		ns.writeLog("SessionManager starts mainroutin.", 1);

		/* Main Loop */
		while(running){

			try { 
				selector.select(); 

				for(SelectionKey key : selector.selectedKeys()){

					if(key.isAcceptable()){
						ns.writeLog("gets acceptable channel", 1);
						REPServerSocketChannel<String> sc = (REPServerSocketChannel<String>) key.channel();
						REPSocketChannel<String> channel;
						channel = sc.accept1();
						//selector.register(channel, SelectionKey.OP_READ, null);
						channel.register(selector, SelectionKey.OP_READ, null);
						ns.writeLog("accepts a client.", 1);

					}else if(key.isReadable()){
						ns.writeLog("gets readable channel", 1);
						//SelectableChannelSimulator<String> channel = key.channel();
						REPSocketChannel<String> channel = (REPSocketChannel<String>) key.channel();
						String packet;
						packet = channel.read();
						ns.writeLog("receives String==> `"+packet+"\'", 1);
						channel.write("from SeMa"+this.getName()+": world");
					}
				}
			}
			catch (IOException e) { e.printStackTrace();}
		}

	}
}