view src/fdl/FDLindaServ.java @ 3:ae7e0e92c651

*** empty log message ***
author fuchita
date Mon, 11 Feb 2008 11:54:15 +0900
parents 083a0b5e12cc
children 2023d9b31af9
line wrap: on
line source


package fdl;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;

public class FDLindaServ implements PSXQueueInterface {
	static final int MAX_REQ = 1;
	static final int FAIL = (-1);
	static final int MAX_UAER = 4;
	static final int MAX_TUPLE = 65536;
	static final int DEF_PORT = 10000;
	static final String PATHNAME = "/tmp/ldserv";
	public static final int TIMEOUT = 5*1000;
	public static Tuple[] tuple_space;
	
	@SuppressWarnings("unchecked")
	public static void main(final String[] args) throws IOException {
		@SuppressWarnings("unused")
		final String usages = "usage: FDLindaServ [-p port]";
		int port = DEF_PORT;

		tuple_space = new Tuple[MAX_TUPLE];
        Selector selector = SelectorProvider.provider().openSelector();		
		//引数判定
		try {
			for (int i=0; i<args.length; ++i) {
				if("-p".equals(args[i])) {
					port = Integer.parseInt(args[++i]);					
				} else {
					System.err.println(usages);
				}
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		
        try {
        	//セレクタを生成


        	//ソケット・チャネルを生成・設定
        	ServerSocketChannel ssChannel = SelectorProvider.provider().openServerSocketChannel();
        	ssChannel.socket().bind(new InetSocketAddress(port));
        	ssChannel.configureBlocking(false);
        	ssChannel.socket().setReuseAddress(true);
        	System.out.println("Server: litening at "+ssChannel);
        	//セレクタにチャンネルを登録
        	//ssChannel.register(selector, SelectionKey.OP_ACCEPT, new AcceptHandler(tuple_space));
            //ssChannel.register(selector, ssChannel.validOps(), new AcceptHandler(tuple_space));
            ssChannel.register(selector, SelectionKey.OP_ACCEPT, new AcceptHandler(tuple_space));
 
        	// セレクタによる監視    
        	while (selector.keys().size() > 0) {
        		@SuppressWarnings("unused")
				int KeyCount = selector.select(TIMEOUT);
        		// Iteratorを用意
        		Iterator it = selector.selectedKeys().iterator();   
        		while (it.hasNext()) {
        			// SelectionKeyを取り出す
        			SelectionKey selKey = (SelectionKey)it.next();
   
        			// 操作に対する処理が行われていると認識させるためにremoveする
        			it.remove();

        			TupleHandler handler = (TupleHandler)selKey.attachment();
        			handler.handle(selKey);
        		}
        		
        	}
        } catch (IOException exc) {
        	exc.printStackTrace();
        } finally {
        	try {
        		for (SelectionKey key: selector.keys()) {
        			key.channel().close();
        		}
        	} catch(IOException ex) {
        		ex.printStackTrace();
        	}
       }
	}
}