List of usage examples for java.nio.channels ServerSocketChannel open
public static ServerSocketChannel open() throws IOException
From source file:net.pms.network.HTTPServer.java
public boolean start() throws IOException { hostname = configuration.getServerHostname(); InetSocketAddress address;/*from ww w . j av a 2 s . c o m*/ if (StringUtils.isNotBlank(hostname)) { logger.info("Using forced address " + hostname); InetAddress tempIA = InetAddress.getByName(hostname); if (tempIA != null && networkInterface != null && networkInterface.equals(NetworkInterface.getByInetAddress(tempIA))) { address = new InetSocketAddress(tempIA, port); } else { address = new InetSocketAddress(hostname, port); } } else if (isAddressFromInterfaceFound(configuration.getNetworkInterface())) { // XXX sets iafinal and networkInterface logger.info("Using address {} found on network interface: {}", iafinal, networkInterface.toString().trim().replace('\n', ' ')); address = new InetSocketAddress(iafinal, port); } else { logger.info("Using localhost address"); address = new InetSocketAddress(port); } logger.info("Created socket: " + address); if (configuration.isHTTPEngineV2()) { // HTTP Engine V2 group = new DefaultChannelGroup("myServer"); factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); ServerBootstrap bootstrap = new ServerBootstrap(factory); HttpServerPipelineFactory pipeline = new HttpServerPipelineFactory(group); bootstrap.setPipelineFactory(pipeline); bootstrap.setOption("child.tcpNoDelay", true); bootstrap.setOption("child.keepAlive", true); bootstrap.setOption("reuseAddress", true); bootstrap.setOption("child.reuseAddress", true); bootstrap.setOption("child.sendBufferSize", 65536); bootstrap.setOption("child.receiveBufferSize", 65536); channel = bootstrap.bind(address); group.add(channel); if (hostname == null && iafinal != null) { hostname = iafinal.getHostAddress(); } else if (hostname == null) { hostname = InetAddress.getLocalHost().getHostAddress(); } } else { // HTTP Engine V1 serverSocketChannel = ServerSocketChannel.open(); serverSocket = serverSocketChannel.socket(); serverSocket.setReuseAddress(true); serverSocket.bind(address); if (hostname == null && iafinal != null) { hostname = iafinal.getHostAddress(); } else if (hostname == null) { hostname = InetAddress.getLocalHost().getHostAddress(); } runnable = new Thread(this, "HTTP Server"); runnable.setDaemon(false); runnable.start(); } return true; }
From source file:org.apache.nifi.io.nio.ChannelListener.java
/** * Adds a server socket channel for listening to connections. * * @param nicIPAddress - if null binds to wildcard address * @param port - port to bind to/*from www .j a v a2s . c o m*/ * @param receiveBufferSize - size of OS receive buffer to request. If less * than 0 then will not be set and OS default will win. * @throws IOException if unable to add socket */ public void addServerSocket(final InetAddress nicIPAddress, final int port, final int receiveBufferSize) throws IOException { final ServerSocketChannel ssChannel = ServerSocketChannel.open(); ssChannel.configureBlocking(false); if (receiveBufferSize > 0) { ssChannel.setOption(StandardSocketOptions.SO_RCVBUF, receiveBufferSize); final int actualReceiveBufSize = ssChannel.getOption(StandardSocketOptions.SO_RCVBUF); if (actualReceiveBufSize < receiveBufferSize) { LOGGER.warn(this + " attempted to set TCP Receive Buffer Size to " + receiveBufferSize + " bytes but could only set to " + actualReceiveBufSize + "bytes. You may want to consider changing the Operating System's " + "maximum receive buffer"); } } ssChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true); ssChannel.bind(new InetSocketAddress(nicIPAddress, port)); ssChannel.register(serverSocketSelector, SelectionKey.OP_ACCEPT); }
From source file:com.saasovation.common.port.adapter.messaging.slothmq.SlothWorker.java
private void openHub() { try {// w w w . java 2s . com this.socket = ServerSocketChannel.open(); this.socket.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), HUB_PORT)); this.socket.configureBlocking(true); this.port = HUB_PORT; logger.info("Opened on port: {}", this.port); } catch (Exception e) { logger.error("Cannot connect because: {}", e.getMessage(), e); } }
From source file:org.jenkinsci.remoting.protocol.IOHubTest.java
@Test public void afterReadyInterestIsCleared() throws Exception { final ServerSocketChannel srv = ServerSocketChannel.open(); srv.bind(new InetSocketAddress(0)); srv.configureBlocking(false);/*from w w w . j a v a 2 s. c o m*/ final AtomicReference<SelectionKey> key = new AtomicReference<SelectionKey>(); final AtomicBoolean oops = new AtomicBoolean(false); hub.hub().register(srv, new IOHubReadyListener() { final AtomicInteger count = new AtomicInteger(0); @Override public void ready(boolean accept, boolean connect, boolean read, boolean write) { if (accept) { try { SocketChannel channel = srv.accept(); channel.write(ByteBuffer.wrap(String.format("Go away #%d", count.incrementAndGet()) .getBytes(Charset.forName("UTF-8")))); channel.close(); } catch (IOException e) { // ignore } } else { oops.set(true); } if (connect || read || write) { oops.set(true); } } }, true, false, false, false, new IOHubRegistrationCallback() { @Override public void onRegistered(SelectionKey selectionKey) { key.set(selectionKey); } @Override public void onClosedChannel(ClosedChannelException e) { } }); Socket client = new Socket(); client.setSoTimeout(100); client.connect(srv.getLocalAddress(), 100); assertThat(IOUtils.toString(client.getInputStream()), is("Go away #1")); client = new Socket(); client.setSoTimeout(100); client.connect(srv.getLocalAddress(), 100); try { assertThat(IOUtils.toString(client.getInputStream()), is("Go away #2")); fail("Expected time-out"); } catch (SocketTimeoutException e) { assertThat(e.getMessage(), containsString("timed out")); } hub.hub().addInterestAccept(key.get()); assertThat(IOUtils.toString(client.getInputStream()), is("Go away #2")); assertThat("Only ever called ready with accept true", oops.get(), is(false)); }
From source file:org.apache.hadoop.mapred.buffer.net.BufferExchangeSink.java
public BufferExchangeSink(JobConf conf, InputCollector<K, V> collector, Task task) throws IOException { this.conf = conf; this.progress = new Progress(); this.ownerid = task.getTaskID(); this.collector = collector; this.maxConnections = conf.getInt("mapred.reduce.parallel.copies", 20); this.task = task; this.numInputs = task.getNumberOfInputs(); this.inputProgress = new HashMap<TaskID, Float>(); this.cursor = new HashMap<TaskID, Position>(); this.syncMapPos = new HashMap<Long, Integer>(); this.syncMaps = conf.getInt("mapred.iterative.partitions", 1); this.syncReducePos = new HashMap<Long, Integer>(); this.syncReduces = conf.getInt("mapred.iterative.partitions", 1); this.executor = Executors.newFixedThreadPool(Math.min(maxConnections, Math.max(numInputs, 5))); this.handlers = Collections.synchronizedSet(new HashSet<Handler>()); this.successful = Collections.synchronizedSet(new HashSet<TaskID>()); /* The server socket and selector registration */ this.server = ServerSocketChannel.open(); this.server.configureBlocking(true); this.server.socket().bind(new InetSocketAddress(0)); }
From source file:morphy.service.SocketConnectionService.java
private SocketConnectionService() { MorphyPreferences morphyPreferences = Morphy.getInstance().getMorphyPreferences(); try {// w ww . j a v a 2 s . com maxCommunicationSizeBytes = morphyPreferences .getInt(PreferenceKeys.SocketConnectionServiceMaxCommunicationBytes); serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); /*Object obj = PreferenceService.getInstance().getProperty(PreferenceKeys.SocketConnectionServicePorts.toString()); System.out.println(obj.getClass()); if (obj instanceof java.util.ArrayList) { //System.out.println((java.util.ArrayList<String>)obj); String[] arr = ((java.util.ArrayList<String>)obj).toArray(new String[0]); System.out.println(java.util.Arrays.toString(arr)); //serverSocketChannel.socket(). for(int i=0;i<arr.length;i++) { serverSocketChannel.socket().bind( new java.net.InetSocketAddress( Integer.parseInt(arr[i]) )); if (LOG.isInfoEnabled()) { LOG.info("Listening on port " + arr[i]); } } } else { if (LOG.isInfoEnabled()) { serverSocketChannel.socket().bind( new java.net.InetSocketAddress( 5000 )); LOG.info("LOAD CONFIG FAILED - Listening on port 5000"); } }*/ serverSocketChannel.socket().bind(new java.net.InetSocketAddress( morphyPreferences.getInt(PreferenceKeys.SocketConnectionServicePorts.toString()))); serverSocketSelector = Selector.open(); serverSocketChannel.register(serverSocketSelector, SelectionKey.OP_ACCEPT); selectionThread = new Thread(selectSocketRunnable); selectionThread.setPriority(Thread.MAX_PRIORITY); selectionThread.start(); LOG.info("Initialized Socket Connection Service host:" + serverSocketChannel.socket().getInetAddress() + " " + serverSocketChannel.socket().getLocalPort()); this.timesealCoder = new TimesealCoder(); } catch (Throwable t) { if (LOG.isErrorEnabled()) LOG.error("Error initializing SocketConnectionService", t); } }
From source file:de.kapsi.net.daap.nio.DaapServerNIO.java
/** * Binds this server to the SocketAddress supplied by DaapConfig * //from w w w.jav a2 s. co m * @throws IOException */ public void bind() throws IOException { SocketAddress bindAddr = config.getInetSocketAddress(); int backlog = config.getBacklog(); try { ssc = ServerSocketChannel.open(); ServerSocket socket = ssc.socket(); // BugID: 4546610 // On Win2k, Mac OS X, XYZ it is possible to bind // the same address without rising a SocketException // (the Documentation lies) socket.setReuseAddress(false); try { socket.bind(bindAddr, backlog); } catch (SocketException err) { throw new BindException(err.getMessage()); } ssc.configureBlocking(false); if (LOG.isInfoEnabled()) { LOG.info("DaapServerNIO bound to " + bindAddr); } streams = new HashSet(); connections = new HashSet(); sessionIds = new HashSet(); } catch (IOException err) { close(); throw err; } }
From source file:Proxy.java
public void start() throws Exception { Map.Entry entry;//ww w . j ava 2 s. c o 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:org.jenkinsci.remoting.protocol.ProtocolStackLoopbackLoadStress.java
public ProtocolStackLoopbackLoadStress(boolean nio, boolean ssl) throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException, UnrecoverableKeyException, KeyManagementException, OperatorCreationException { KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA"); gen.initialize(2048); // maximum supported by JVM with export restrictions keyPair = gen.generateKeyPair();// w w w . jav a 2 s.c om Date now = new Date(); Date firstDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(10)); Date lastDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(-10)); SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo .getInstance(keyPair.getPublic().getEncoded()); X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); X500Name subject = nameBuilder.addRDN(BCStyle.CN, getClass().getSimpleName()).addRDN(BCStyle.C, "US") .build(); X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(subject, BigInteger.ONE, firstDate, lastDate, subject, subjectPublicKeyInfo); JcaX509ExtensionUtils instance = new JcaX509ExtensionUtils(); certGen.addExtension(X509Extension.subjectKeyIdentifier, false, instance.createSubjectKeyIdentifier(subjectPublicKeyInfo)); ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BOUNCY_CASTLE_PROVIDER) .build(keyPair.getPrivate()); certificate = new JcaX509CertificateConverter().setProvider(BOUNCY_CASTLE_PROVIDER) .getCertificate(certGen.build(signer)); char[] password = "password".toCharArray(); KeyStore store = KeyStore.getInstance("jks"); store.load(null, password); store.setKeyEntry("alias", keyPair.getPrivate(), password, new Certificate[] { certificate }); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(store, password); context = SSLContext.getInstance("TLS"); context.init(kmf.getKeyManagers(), new TrustManager[] { new PublicKeyMatchingX509ExtendedTrustManager(keyPair.getPublic()) }, null); hub = IOHub.create(executorService); serverSocketChannel = ServerSocketChannel.open(); acceptor = new Acceptor(serverSocketChannel, nio, ssl); }
From source file:uk.ac.horizon.ubihelper.service.PeerManager.java
public PeerManager(Service service) { this.service = service; // Note: meant to open database on another thread?! database = new PeersOpenHelper(service).getWritableDatabase(); protocol = new MyProtocolManager(); peerConnectionListener = new OnPeerConnectionListener(protocol); remoteChannelTimer = new Timer(); wifi = (WifiManager) service.getSystemService(Service.WIFI_SERVICE); try {/*from w ww. j a v a 2s . com*/ messageDigest = MessageDigest.getInstance("MD5"); } catch (Exception e) { Log.e(TAG, "Could not get MessageDigest: " + e); } try { serverSocketChannel = ServerSocketChannel.open(); ServerSocket ss = serverSocketChannel.socket(); ss.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0)); serverPort = ss.getLocalPort(); serverSocketChannel.configureBlocking(false); } catch (IOException e) { Log.w(TAG, "Error opening ServerSocketChannel: " + e.getMessage()); } try { selector = new PeerConnectionScheduler(serverSocketChannel); selector.setListener(selectorListener); selector.start(); } catch (IOException e) { Log.w(TAG, "Error starting Selector: " + e.getMessage()); } }