List of usage examples for java.nio.channels Selector open
public static Selector open() throws IOException
From source file:org.pvalsecc.comm.MultiplexedServer.java
/** * Attempt to create the listening socket for at most 5 minutes. *///from w ww .ja va2 s .c o m private void createSocket() { while (!stop) { ServerSocketChannel serverSocketChannel = null; try { synchronized (selectorLOCK) { if (!stop) { selector = Selector.open(); } } if (!stop) { serverSocketChannel = ServerSocketChannel.open(); //serverSocketChannel.socket().setReuseAddress(true); serverSocketChannel.configureBlocking(false); serverSocketChannel.socket().bind(address); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); LOGGER.info("[" + threadName + "] Start to listen on " + address); } break; } catch (IOException e) { //noinspection StringContatenationInLoop LOGGER.warn("Cannot start to listen on " + threadName + " (will try again later)", e); SystemUtilities.safeClose(serverSocketChannel); try { Thread.sleep(5000); } catch (InterruptedException ignored) { //ignored } } } }
From source file:x10.x10rt.yarn.ApplicationMaster.java
public ApplicationMaster(String[] args) throws Exception { this.conf = new YarnConfiguration(); Map<String, String> envs = System.getenv(); ContainerId containerId = ConverterUtils.toContainerId(envs.get(Environment.CONTAINER_ID.name())); appAttemptID = containerId.getApplicationAttemptId(); LOG.info("Application master for app" + ", appId=" + appAttemptID.getApplicationId().getId() + ", clustertimestamp=" + appAttemptID.getApplicationId().getClusterTimestamp() + ", attemptId=" + appAttemptID.getAttemptId()); initialNumPlaces = Integer.parseInt(envs.get(X10_NPLACES)); coresPerPlace = Integer.parseInt(envs.get(X10_NTHREADS)); nthreads = coresPerPlace;// ww w . j a v a2 s.c o m links = new HashMap<Integer, ApplicationMaster.CommunicationLink>(initialNumPlaces); places = new HashMap<ContainerId, Integer>(initialNumPlaces); pendingReads = new HashMap<SocketChannel, ByteBuffer>(); selector = Selector.open(); this.args = args; this.appName = System.getProperty(X10_YARN_MAIN); // look for max memory argument this.memoryPerPlaceInMb = 4024; // default of 1Gb per place for (int i = 0; i < args.length; i++) { try { if (args[i].startsWith("-Xmx")) { if (args[i].toLowerCase().endsWith("g")) this.memoryPerPlaceInMb = Integer.parseInt(args[i].substring(4, args[i].length() - 1)) * 1024; else if (args[i].toLowerCase().endsWith("m")) this.memoryPerPlaceInMb = Integer.parseInt(args[i].substring(4, args[i].length() - 1)); else if (args[i].toLowerCase().endsWith("k")) this.memoryPerPlaceInMb = Integer.parseInt(args[i].substring(4, args[i].length() - 1)) / 1024; else this.memoryPerPlaceInMb = Integer.parseInt(args[i].substring(4)) / 1024 / 1024; break; } } catch (NumberFormatException e) { // ignore, use default value e.printStackTrace(); } } if (envs.containsKey(X10YARNENV_ + X10_YARN_KILL)) { placeKiller = new ScheduledThreadPoolExecutor(1); // things to kill takes the form place:delayInSeconds,place:delayInSeconds,etc. e.g. "2:2,3:3" will kill place 2 after 2 seconds, 3 after 3 seconds String thingsToKill = System.getenv(X10YARNENV_ + X10_YARN_KILL); // TODO: format error checking String[] sets = thingsToKill.split(","); pendingKills = new HashMap<Integer, Integer>(sets.length); for (String set : sets) { String[] place_delay = set.split(":"); int place = Integer.parseInt(place_delay[0]); int delay = Integer.parseInt(place_delay[1]); pendingKills.put(place, delay); } } else { placeKiller = null; pendingKills = null; } }
From source file:org.cryptomator.ui.util.SingleInstanceManager.java
/** * Creates a server socket on a free port and saves the port in * {@link Preferences#userNodeForPackage(Class)} for {@link Main} under the * given applicationKey.//from w w w. j a v a 2 s . c o m * * @param applicationKey * key used to save the port and identify upon connection. * @param exec * the task which is submitted is interruptable. * @return * @throws IOException */ public static LocalInstance startLocalInstance(String applicationKey, ExecutorService exec) throws IOException { final ServerSocketChannel channel = ServerSocketChannel.open(); channel.configureBlocking(false); channel.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0)); final int port = ((InetSocketAddress) channel.getLocalAddress()).getPort(); Preferences.userNodeForPackage(Main.class).putInt(applicationKey, port); LOG.info("InstanceManager bound to port {}", port); Selector selector = Selector.open(); channel.register(selector, SelectionKey.OP_ACCEPT); LocalInstance instance = new LocalInstance(applicationKey, channel, selector); exec.submit(() -> { try { instance.port = ((InetSocketAddress) channel.getLocalAddress()).getPort(); } catch (IOException e) { } instance.selectionLoop(); }); return instance; }
From source file:Proxy.java
void _handleConnection(final SocketChannel in_channel, final SocketChannel out_channel) throws Exception { executor.execute(new Runnable() { public void run() { Selector sel = null;//from w w w . j a v a 2 s . c om SocketChannel tmp; Set ready_keys; SelectionKey key; ByteBuffer transfer_buf = ByteBuffer.allocate(BUFSIZE); try { sel = Selector.open(); in_channel.configureBlocking(false); out_channel.configureBlocking(false); in_channel.register(sel, SelectionKey.OP_READ); out_channel.register(sel, SelectionKey.OP_READ); while (sel.select() > 0) { ready_keys = sel.selectedKeys(); for (Iterator it = ready_keys.iterator(); it.hasNext();) { key = (SelectionKey) it.next(); it.remove(); // remove current entry (why ?) tmp = (SocketChannel) key.channel(); if (tmp == null) { log("Proxy._handleConnection()", "attachment is null, continuing"); continue; } if (key.isReadable()) { // data is available to be read from tmp if (tmp == in_channel) { // read all data from in_channel and forward it to out_channel (request) if (relay(tmp, out_channel, transfer_buf) == false) return; } if (tmp == out_channel) { // read all data from out_channel and forward it // to in_channel (response) if (relay(tmp, in_channel, transfer_buf) == false) return; } } } } } catch (Exception ex) { ex.printStackTrace(); } finally { close(sel, in_channel, out_channel); } } }); }
From source file:org.cryptomator.ui.util.SingleInstanceManager.java
/** * tries to fill the given buffer for the given time * //from w w w . j a va 2 s. co m * @param channel * @param buf * @param timeout * @throws ClosedChannelException * @throws IOException */ public static <T extends SelectableChannel & ReadableByteChannel> void tryFill(T channel, final ByteBuffer buf, int timeout) throws IOException { if (channel.isBlocking()) { throw new IllegalStateException("Channel is in blocking mode."); } try (Selector selector = Selector.open()) { channel.register(selector, SelectionKey.OP_READ); TimeoutTask.attempt(remainingTime -> { if (!buf.hasRemaining()) { return true; } if (selector.select(remainingTime) > 0) { if (channel.read(buf) < 0) { return true; } } return !buf.hasRemaining(); }, timeout, 1); } }
From source file:net.lightbody.bmp.proxy.jetty.http.nio.SocketChannelListener.java
public void start() throws Exception { if (isStarted()) throw new IllegalStateException("Started"); // Create a new server socket and set to non blocking mode _acceptChannel = ServerSocketChannel.open(); _acceptChannel.configureBlocking(false); // Bind the server socket to the local host and port _acceptChannel.socket().bind(_address); // Read the address back from the server socket to fix issues // with listeners on anonymous ports _address = (InetSocketAddress) _acceptChannel.socket().getLocalSocketAddress(); // create a selector; _selector = Selector.open(); // Register accepts on the server socket with the selector. _acceptChannel.register(_selector, SelectionKey.OP_ACCEPT); // Start selector thread _selectorThread = new SelectorThread(); _selectorThread.start();/*from w w w . j a v a2 s.c om*/ // Start the thread Pool super.start(); log.info("Started SocketChannelListener on " + getHost() + ":" + getPort()); }
From source file:com.springrts.springls.ServerThread.java
public boolean startServer() { context.starting();/* w ww. ja v a 2 s.c o m*/ Configuration configuration = getContext().getService(Configuration.class); int port = configuration.getInt(ServerConfiguration.PORT); try { context.getServer().setCharset("ISO-8859-1"); // open a non-blocking server socket channel sSockChan = ServerSocketChannel.open(); sSockChan.configureBlocking(false); // bind to localhost on designated port //***InetAddress addr = InetAddress.getLocalHost(); //***sSockChan.socket().bind(new InetSocketAddress(addr, port)); sSockChan.socket().bind(new InetSocketAddress(port)); // get a selector for multiplexing the client channels readSelector = Selector.open(); } catch (IOException ex) { LOG.error("Could not listen on port: " + port, ex); return false; } LOG.info("Listening for connections on TCP port {} ...", port); context.started(); return true; }
From source file:de.kapsi.net.daap.nio.DaapServerNIO.java
/** * The run loop//from w w w. jav a 2 s .c o m */ public void run() { try { if (running) { LOG.error("DaapServerNIO is already running."); return; } selector = Selector.open(); SelectionKey sk = ssc.register(selector, SelectionKey.OP_ACCEPT); process(); } catch (IOException err) { LOG.error(err); throw new RuntimeException(err); } finally { close(); } }
From source file:org.openhab.binding.tcp.AbstractDatagramChannelBinding.java
/** * Activate./*from ww w . j a va2 s .c o m*/ */ public void activate() { //register the selectors try { selector = Selector.open(); } catch (IOException e) { logger.error("An exception occurred while registering the selector: {}", e.getMessage()); } }
From source file:org.quickserver.net.server.QuickServer.java
/** * Returns a ServerSocket object to be used for listening. * @since 1.4.0/* ww w .j a va 2 s .c o m*/ */ protected void makeServerSocket() throws BindException, IOException { server = null; logger.log(Level.FINEST, "Binding {0} to IP: {1}", new Object[] { getName(), getBindAddr() }); InetSocketAddress bindAddress = new InetSocketAddress(getBindAddr(), getPort()); try { NetworkInterface ni = NetworkInterface.getByInetAddress(getBindAddr()); if (ni != null) { logger.fine("NetworkInterface: " + ni); } } catch (Exception igrnore) { /*ignore*/} catch (Error igrnore) { /*ignore*/} if (getSecure().isEnable() == false) { logger.log(Level.FINE, "Making a normal ServerSocket for {0}", getName()); setRunningSecure(false); if (getBlockingMode() == false) { //for non-blocking serverSocketChannel = ServerSocketChannel.open(); server = serverSocketChannel.socket(); server.bind(bindAddress, getBasicConfig().getAdvancedSettings().getBacklog()); } else { //for blocking server = new ServerSocket(getPort(), getBasicConfig().getAdvancedSettings().getBacklog(), getBindAddr()); } } else { try { logger.log(Level.FINE, "Making a secure ServerSocket for {0}", getName()); getSSLContext(); setRunningSecure(true); if (getBlockingMode() == false) { logger.log(Level.FINE, "Making a secure ServerSocketChannel for {0}", getName()); //for non-blocking serverSocketChannel = ServerSocketChannel.open(); server = serverSocketChannel.socket(); server.bind(bindAddress, getBasicConfig().getAdvancedSettings().getBacklog()); } else { ServerSocketFactory ssf = getSSLContext().getServerSocketFactory(); SSLServerSocket serversocket = (SSLServerSocket) ssf.createServerSocket(getPort(), getBasicConfig().getAdvancedSettings().getBacklog(), getBindAddr()); serversocket.setNeedClientAuth(secure.isClientAuthEnable()); setRunningSecure(true); secureStoreManager.logSSLServerSocketInfo(serversocket); server = serversocket; serverSocketChannel = server.getChannel(); if (serverSocketChannel == null && getBlockingMode() == false) { logger.warning("Secure Server does not support Channel! So will run in blocking mode."); blockingMode = false; } } //blocking } catch (NoSuchAlgorithmException e) { logger.log(Level.WARNING, "NoSuchAlgorithmException : {0}", e); throw new IOException("Error creating secure socket : " + e.getMessage()); } catch (KeyManagementException e) { logger.log(Level.WARNING, "KeyManagementException : {0}", e); throw new IOException("Error creating secure socket : " + e.getMessage()); } } server.setReuseAddress(true); int connectionTime = 0; int latency = 0; int bandwidth = 0; connectionTime = getBasicConfig().getAdvancedSettings().getPerformancePreferencesConnectionTime(); latency = getBasicConfig().getAdvancedSettings().getPerformancePreferencesLatency(); bandwidth = getBasicConfig().getAdvancedSettings().getPerformancePreferencesBandwidth(); logger.log(Level.FINE, "getPerformancePreferencesConnectionTime : {0}", connectionTime); logger.log(Level.FINE, "getPerformancePreferencesLatency : {0}", latency); logger.log(Level.FINE, "getPerformancePreferencesBandwidth : {0}", bandwidth); server.setPerformancePreferences(connectionTime, latency, bandwidth); int clientSocketReceiveBufferSize = getBasicConfig().getAdvancedSettings() .getClientSocketReceiveBufferSize(); if (clientSocketReceiveBufferSize > 0) { logger.log(Level.FINE, "clientSocketReceiveBufferSize: {0}", clientSocketReceiveBufferSize); server.setReceiveBufferSize(clientSocketReceiveBufferSize); } if (getBlockingMode() == false) { logger.log(Level.FINE, "Server Mode {0} - Non Blocking", getName()); if (selector == null || selector.isOpen() == false) { logger.finest("Opening new selector"); selector = Selector.open(); } else { logger.log(Level.FINEST, "Reusing selector: {0}", selector); } serverSocketChannel.configureBlocking(false); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); selector.wakeup(); } else { logger.log(Level.FINE, "Server Mode {0} - Blocking", getName()); } }