Mercurial > hg > FederatedLinda
view src/fdl/IOHandler.java @ 37:2a366abc3f1f
*** empty log message ***
author | kono |
---|---|
date | Sun, 24 Aug 2008 21:21:40 +0900 |
parents | fe338d497c72 |
children | 81abceebc869 |
line wrap: on
line source
package fdl; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.ClosedChannelException; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; public class IOHandler implements TupleHandler { static final boolean debug = true; public TupleSpace tupleSpace; public SocketChannel ch; String remoteString; String localString; public int cnt = 0; public IOHandler(TupleSpace tupleSpace,SocketChannel ch) { this.tupleSpace = tupleSpace; remoteString = PSX.getRemoteHostAndPort(ch); localString = PSX.getLocalHostAndPort(ch); this.ch = ch; } public void handle(SelectionKey key) { // 書き込み可であれば,読み込みを行う if (key.isReadable()) { try { read(key); } catch (ClosedChannelException e) { key.cancel(); tupleSpace.hook.closeHook(key); } catch (IOException e) { key.cancel(); tupleSpace.hook.closeHook(key); } } } void read(SelectionKey key) throws ClosedChannelException, IOException { SocketChannel channel = (SocketChannel)key.channel(); if (ch!=channel) { System.err.println("Wrong socket on IOHandler"); } // 読み込み用のバッファの生成 ByteBuffer command = ByteBuffer.allocate(PSX.LINDA_HEADER_SIZE); command.order(ByteOrder.BIG_ENDIAN); ByteBuffer data = PSX.receivePacket(channel, command); if (debug) { PSX.printData("IOHandler:",command); } manager_run(key, command, data); // assert((key.interestOps()& SelectionKey.OP_READ) !=0); } public void manager_run(SelectionKey key, ByteBuffer command, ByteBuffer data) throws IOException { command.order(ByteOrder.BIG_ENDIAN); int mode = command.get(PSX.LINDA_MODE_OFFSET); command.rewind(); if (debug) { System.out.println("data from : "+key.channel()); } if(mode == '!') { tupleSpace.hook.closeHook(key); } else if(mode == PSX.PSX_CHECK) { tupleSpace.Check(key, command); } else if(mode == PSX.PSX_IN || mode == PSX.PSX_RD){ tupleSpace.In_Rd(key, command, mode); } else if (mode == PSX.PSX_WAIT_RD) { tupleSpace.Wait_Rd(key, command, mode); } else if(mode == PSX.PSX_OUT) { tupleSpace.Out(key, command, data); } else { tupleSpace.hook.closeHook(key); System.err.println("Incorrect tuple operation"); System.exit(1); } } void Connection_Close(SelectionKey key) throws IOException { System.out.println("Connection closed by "+key.channel()); SocketChannel channel = (SocketChannel)key.channel(); key.cancel(); channel.close(); } }