1 46 package org.mr.core.net; 47 48 56 57 import java.io.IOException ; 58 import java.net.SocketException ; 59 import java.net.InetAddress ; 60 import java.net.InetSocketAddress ; 61 import java.net.SocketAddress ; 62 import java.nio.channels.ServerSocketChannel ; 63 64 public class LocalTCPTransport implements LocalTransport { 65 private TransportInfo info; 66 private ServerSocketChannel channel; 67 68 private NetworkSelector selector; 69 70 73 public LocalTCPTransport(TransportType type, InetAddress addr, int portMin, 74 int portMax, NetworkSelector selector) 75 throws IOException 76 { 77 if (portMin > portMax) { 78 throw new IllegalArgumentException ("Illegal port range: " + 79 portMin + "-" + portMax); 80 } 81 82 this.selector = selector; 83 this.channel = ServerSocketChannel.open(); 84 85 boolean success = false; 86 InetSocketAddress bindAddr = null; 87 int port = portMin; 88 IOException savedException = null; 89 90 while (port <= portMax && !success) { 91 bindAddr = new InetSocketAddress (addr, port++); 92 try { 93 this.channel.socket().bind(bindAddr); 94 success = true; 95 } catch (SocketException e) { 96 savedException = e; 97 } 98 } 99 if (success) { 100 this.channel.configureBlocking(false); 101 this.info = new TransportInfo(bindAddr, type); 102 } else { 103 throw savedException; 104 } 105 } 106 107 111 public TransportInfo getInfo() { 112 return this.info; 113 } 114 115 public SocketAddress getSocketAddress() { 116 if (this.channel != null) { 117 return this.channel.socket().getLocalSocketAddress(); 118 } else { 119 return getInfo().getSocketAddress(); 120 } 121 } 122 123 public TransportType getTransportType() { 124 return info.getTransportInfoType(); 125 } 126 127 public void open() { 128 this.selector.addServerChannel(this.channel); 129 } 130 131 public void close() { 132 try { 133 this.channel.close(); 134 } catch (Exception e) { 135 } 137 } 138 } | Popular Tags |