List of usage examples for java.nio.channels ServerSocketChannel socket
public abstract ServerSocket socket();
From source file:jp.queuelinker.system.net.SelectorThread.java
public int openServerSocket(final InetSocketAddress bindAddress, final SelectorCallBack callBack) throws IOException { ServerSocketChannel serverChannel = ServerSocketChannel.open(); serverChannel.configureBlocking(false); serverChannel.socket().setReuseAddress(true); serverChannel.socket().bind(bindAddress); return addSocketChannel(serverChannel, callBack); }
From source file:com.byteatebit.nbserver.simple.tcp.TcpConnectorFactory.java
@Override public IConnector create(ISelectorRegistrarBalancer selectorRegistrarBalancer, IComputeTaskScheduler taskScheduler, SocketAddress listenAddress) throws IOException { Preconditions.checkNotNull(selectorRegistrarBalancer, "selectorRegistrarBalancer cannot be null"); Preconditions.checkNotNull(taskScheduler, "taskScheduler cannot be null"); Preconditions.checkNotNull(listenAddress, "listenAddress cannot be null"); // open the server socketChannel ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); IOTimeoutTask timeoutTask = (selectionKey, ops) -> { LOG.error("selectionKey timeout"); selectionKey.cancel();//from w w w . j a va 2 s. c o m IOUtils.closeQuietly(selectionKey.channel()); }; for (SocketOptionValue socketOptionValue : socketOptionValues) serverSocketChannel.setOption(socketOptionValue.getOption(), socketOptionValue.getValue()); SelectionKey serverSocketSelectionKey = selectorRegistrarBalancer.getSelectorRegistrar().register( serverSocketChannel, SelectionKey.OP_ACCEPT, selectionKey -> connectHandler.accept( new NbContext(selectorRegistrarBalancer.getSelectorRegistrar(), taskScheduler), selectionKey, serverSocketChannel), timeoutTask, -1); serverSocketChannel.socket().bind(listenAddress, maxServerSocketBacklog); return new TcpConnector(serverSocketSelectionKey, serverSocketChannel); }
From source file:com.sun.grizzly.http.jk.common.ChannelNioSocket.java
/** * jmx:managed-operation// w ww.j a va 2s .c om */ @Override public void init() throws IOException { // Find a port. if (startPort == 0) { port = 0; LoggerUtils.getLogger().info("JK: ajp13 disabling channelNioSocket"); running = true; return; } if (maxPort < startPort) { maxPort = startPort; } ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.configureBlocking(false); for (int i = startPort; i <= maxPort; i++) { try { InetSocketAddress iddr = null; if (inet == null) { iddr = new InetSocketAddress(i); } else { iddr = new InetSocketAddress(inet, i); } sSocket = ssc.socket(); sSocket.bind(iddr); port = i; break; } catch (IOException ex) { LoggerUtils.getLogger().info("Port busy " + i + " " + ex.toString()); sSocket = null; } } if (sSocket == null) { LoggerUtils.getLogger().log(Level.SEVERE, "Can't find free port " + startPort + " " + maxPort); return; } LoggerUtils.getLogger().info("JK: ajp13 listening on " + getAddress() + ":" + port); selector = Utils.openSelector(); ssc.register(selector, SelectionKey.OP_ACCEPT); // If this is not the base port and we are the 'main' channleSocket and // SHM didn't already set the localId - we'll set the instance id if ("channelNioSocket".equals(name) && port != startPort && (wEnv.getLocalId() == 0)) { wEnv.setLocalId(port - startPort); } // XXX Reverse it -> this is a notification generator !! if (next == null && wEnv != null) { if (nextName != null) { setNext(wEnv.getHandler(nextName)); } if (next == null) { next = wEnv.getHandler("dispatch"); } if (next == null) { next = wEnv.getHandler("request"); } } JMXRequestNote = wEnv.getNoteId(WorkerEnv.ENDPOINT_NOTE, "requestNote"); running = true; // Run a thread that will accept connections. // XXX Try to find a thread first - not sure how... if (this.domain != null) { try { tpOName = new ObjectName(domain + ":type=ThreadPool,name=" + getChannelName()); Registry.getRegistry(null, null).registerComponent(tp, tpOName, null); rgOName = new ObjectName(domain + ":type=GlobalRequestProcessor,name=" + getChannelName()); Registry.getRegistry(null, null).registerComponent(global, rgOName, null); } catch (Exception e) { LoggerUtils.getLogger().log(Level.SEVERE, "Can't register threadpool"); } } tp.start(); Poller pollAjp = new Poller(); tp.runIt(pollAjp); }
From source file:Proxy.java
public void start() throws Exception { Map.Entry entry;/*from w ww. j a v a 2s . co m*/ Selector selector; ServerSocketChannel sock_channel; MyInetSocketAddress key, value; if (remote != null && local != null) mappings.put(new InetSocketAddress(local, local_port), new InetSocketAddress(remote, remote_port)); if (mapping_file != null) { try { populateMappings(mapping_file); } catch (Exception ex) { log("Failed reading " + mapping_file); throw ex; } } log("\nProxy started at " + new java.util.Date()); if (verbose) { log("\nMappings:\n---------"); for (Iterator it = mappings.entrySet().iterator(); it.hasNext();) { entry = (Map.Entry) it.next(); log(toString((InetSocketAddress) entry.getKey()) + " <--> " + toString((InetSocketAddress) entry.getValue())); } log("\n"); } // 1. Create a Selector selector = Selector.open(); // Create a thread pool (Executor) executor = new ThreadPoolExecutor(MIN_THREAD_POOL_SIZE, MAX_THREAD_POOL_SIZE, 30000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(1000)); for (Iterator it = mappings.keySet().iterator(); it.hasNext();) { key = (MyInetSocketAddress) it.next(); value = (MyInetSocketAddress) mappings.get(key); // if either source or destination are SSL, we cannot use JDK 1.4 // NIO selectors, but have to fall back on separate threads per connection if (key.ssl() || value.ssl()) { // if(2 == 2) { SocketAcceptor acceptor = new SocketAcceptor(key, value); executor.execute(acceptor); continue; } // 2. Create a ServerSocketChannel sock_channel = ServerSocketChannel.open(); sock_channel.configureBlocking(false); sock_channel.socket().bind(key); // 3. Register the selector with all server sockets. 'Key' is attachment, so we get it again on // select(). That way we can associate it with the mappings hashmap to find the corresponding // value sock_channel.register(selector, SelectionKey.OP_ACCEPT, key); } // 4. Start main loop. won't return until CTRL-C'ed loop(selector); }
From source file:net.ymate.platform.serv.nio.support.NioEventGroup.java
protected SelectableChannel __doChannelCreate(INioServerCfg cfg) throws IOException { ServerSocketChannel _channel = ServerSocketChannel.open(); _channel.configureBlocking(false);// w ww . ja va 2 s. co m _channel.socket().bind(new InetSocketAddress(cfg.getServerHost(), cfg.getPort())); return _channel; }
From source file:org.apache.catalina.cluster.tcp.ReplicationListener.java
public void listen() throws Exception { doListen = true;/*from w ww . j a v a2 s . co m*/ // allocate an unbound server socket channel ServerSocketChannel serverChannel = ServerSocketChannel.open(); // Get the associated ServerSocket to bind it with ServerSocket serverSocket = serverChannel.socket(); // create a new Selector for use below Selector selector = Selector.open(); // set the port the server channel will listen to serverSocket.bind(new InetSocketAddress(bind, port)); // set non-blocking mode for the listening socket serverChannel.configureBlocking(false); // register the ServerSocketChannel with the Selector serverChannel.register(selector, SelectionKey.OP_ACCEPT); while (doListen) { // this may block for a long time, upon return the // selected set contains keys of the ready channels try { //System.out.println("Selecting with timeout="+timeout); int n = selector.select(timeout); //System.out.println("select returned="+n); if (n == 0) { continue; // nothing to do } // get an iterator over the set of selected keys Iterator it = selector.selectedKeys().iterator(); // look at each key in the selected set while (it.hasNext()) { SelectionKey key = (SelectionKey) it.next(); // Is a new connection coming in? if (key.isAcceptable()) { ServerSocketChannel server = (ServerSocketChannel) key.channel(); SocketChannel channel = server.accept(); registerChannel(selector, channel, SelectionKey.OP_READ, new ObjectReader(channel, selector, callback)); } // is there data to read on this channel? //System.out.println("key readable="+key.isReadable()); if (key.isReadable()) { readDataFromSocket(key); } else { //System.out.println("This shouldn't get called"); key.interestOps(key.interestOps() & (~key.OP_WRITE)); } // remove key from selected set, it's been handled it.remove(); } //System.out.println("Done with loop"); } catch (java.nio.channels.CancelledKeyException nx) { log.warn("Replication client disconnected, error when polling key. Ignoring client."); } catch (Exception x) { log.error("Unable to process request in ReplicationListener", x); } } //while serverChannel.close(); selector.close(); }
From source file:org.apache.geode.internal.net.SocketCreator.java
/** * Creates or bind server socket to a random port selected from tcp-port-range which is same as * membership-port-range.//from ww w . jav a 2s .co m * * @param ba * @param backlog * @param isBindAddress * @param tcpBufferSize * @param sslConnection whether to connect using SSL * * @return Returns the new server socket. * * @throws IOException */ public ServerSocket createServerSocketUsingPortRange(InetAddress ba, int backlog, boolean isBindAddress, boolean useNIO, int tcpBufferSize, int[] tcpPortRange, boolean sslConnection) throws IOException { ServerSocket socket = null; int localPort = 0; int startingPort = 0; // Get a random port from range. Random rand = new SecureRandom(); int portLimit = tcpPortRange[1]; int randPort = tcpPortRange[0] + rand.nextInt(tcpPortRange[1] - tcpPortRange[0] + 1); startingPort = randPort; localPort = startingPort; while (true) { if (localPort > portLimit) { if (startingPort != 0) { localPort = tcpPortRange[0]; portLimit = startingPort - 1; startingPort = 0; } else { throw new SystemConnectException( LocalizedStrings.TCPConduit_UNABLE_TO_FIND_FREE_PORT.toLocalizedString()); } } try { if (useNIO) { ServerSocketChannel channl = ServerSocketChannel.open(); socket = channl.socket(); InetSocketAddress addr = new InetSocketAddress(isBindAddress ? ba : null, localPort); socket.bind(addr, backlog); } else { socket = this.createServerSocket(localPort, backlog, isBindAddress ? ba : null, tcpBufferSize, sslConnection); } break; } catch (java.net.SocketException ex) { if (useNIO || SocketCreator.treatAsBindException(ex)) { localPort++; } else { throw ex; } } } return socket; }
From source file:org.apache.hadoop.hbase.TestIPv6NIOServerSocketChannel.java
/** * Creates a NIO ServerSocketChannel, and gets the ServerSocket from * there. Then binds the obtained socket. * This fails on Windows with Oracle JDK1.6.0u33, if the passed InetAddress is a * IPv6 address. Works on Oracle JDK 1.7. *//*from w w w.j a v a 2s . c o m*/ private void bindNIOServerSocket(InetAddress inetAddr) throws IOException { while (true) { int port = HBaseTestingUtility.randomFreePort(); InetSocketAddress addr = new InetSocketAddress(inetAddr, port); ServerSocketChannel channel = null; ServerSocket serverSocket = null; try { channel = ServerSocketChannel.open(); serverSocket = channel.socket(); serverSocket.bind(addr); // This does not work break; } catch (BindException ex) { //continue } finally { if (serverSocket != null) { serverSocket.close(); } if (channel != null) { channel.close(); } } } }
From source file:org.apache.nifi.processor.util.listen.dispatcher.SocketChannelDispatcher.java
@Override public void open(final InetAddress nicAddress, final int port, final int maxBufferSize) throws IOException { stopped = false;//from ww w . j ava2 s . co m executor = Executors.newFixedThreadPool(maxConnections); final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); if (maxBufferSize > 0) { serverSocketChannel.setOption(StandardSocketOptions.SO_RCVBUF, maxBufferSize); final int actualReceiveBufSize = serverSocketChannel.getOption(StandardSocketOptions.SO_RCVBUF); if (actualReceiveBufSize < maxBufferSize) { logger.warn("Attempted to set Socket Buffer Size to " + maxBufferSize + " bytes but could only set to " + actualReceiveBufSize + "bytes. You may want to consider changing the Operating System's " + "maximum receive buffer"); } } serverSocketChannel.socket().bind(new InetSocketAddress(nicAddress, port)); selector = Selector.open(); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); }
From source file:org.cloudata.core.commitlog.CommitLogServer.java
private int startFileTransferChannel(String dirName, FileChannel[] fileChannelList) { int port = -1; try {/*from w w w. ja v a 2 s .c o m*/ ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.configureBlocking(false); ServerSocket serverSocket = ssc.socket(); serverSocket.bind(null); port = serverSocket.getLocalPort(); new FileTransferThread(dirName, ssc, fileChannelList).start(); //LOG.info("File transfer thread is started and read method is done"); } catch (IOException e) { LOG.warn("starting file transfer is fail", e); } return port; }