1 package org.sapia.ubik.net.nio.tcp.acceptor; 2 3 import java.io.IOException ; 4 import java.net.InetSocketAddress ; 5 import java.nio.ByteBuffer ; 6 import java.nio.channels.Channel ; 7 import java.nio.channels.SelectionKey ; 8 import java.nio.channels.Selector ; 9 import java.nio.channels.ServerSocketChannel ; 10 import java.nio.channels.SocketChannel ; 11 12 import org.sapia.ubik.net.nio.ChannelHandler; 13 import org.sapia.ubik.net.nio.ChannelHandlerFactory; 14 import org.sapia.ubik.net.nio.ChannelManager; 15 16 28 public class TCPChannelManager implements ChannelManager { 29 30 private InetSocketAddress _addr; 31 private ChannelHandlerFactory _factory; 32 33 public TCPChannelManager(InetSocketAddress addr, ChannelHandlerFactory factory){ 34 _addr = addr; 35 _factory = factory; 36 } 37 38 41 public Channel create() throws IOException { 42 ServerSocketChannel chan = ServerSocketChannel.open(); 43 chan.socket().bind(_addr); 44 chan.configureBlocking(true); 45 return chan; 46 } 47 48 51 public Channel accept(Channel server) throws IOException { 52 SocketChannel client = ((ServerSocketChannel )server).accept(); 53 if(client == null){ 54 return null; 55 } 56 client.configureBlocking(false); 57 return client; 58 } 59 60 63 public Object getAddress(Channel server) throws UnsupportedOperationException { 64 return ((ServerSocketChannel )server).socket().getInetAddress(); 65 } 66 67 70 public SelectionKey register(Channel channel, Selector selector, int ops, Object attachment) throws IOException { 71 if(attachment == null){ 72 return ((SocketChannel )channel).register(selector, ops); 73 } 74 else{ 75 return ((SocketChannel )channel).register(selector, ops, attachment); 76 } 77 } 78 79 82 public int read(Channel from, ByteBuffer to) throws IOException { 83 return ((SocketChannel )from).read(to); 84 } 85 86 89 public int write(Channel to, ByteBuffer from) throws IOException { 90 return ((SocketChannel )to).write(from); 91 } 92 93 96 public ChannelHandler createHandler() { 97 return _factory.createHandler(); 98 } 99 } 100 | Popular Tags |