Java Code Examples for java.nio.channels.ServerSocketChannel#open()
The following examples show how to use
java.nio.channels.ServerSocketChannel#open() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Server.java From TarsJava with BSD 3-Clause "New" or "Revised" License | 6 votes |
protected void startNIOServer() throws Exception { SelectableChannel server = null; int interestKey; //1. Start reactor service selectorManager.start(); //2. Start server on the specified port if (this.udpMode) { server = DatagramChannel.open(); ((DatagramChannel) server).socket().bind(new InetSocketAddress(host, port)); interestKey = SelectionKey.OP_READ; } else { server = ServerSocketChannel.open(); ((ServerSocketChannel) server).socket().bind(new InetSocketAddress(host, port), 1024); interestKey = SelectionKey.OP_ACCEPT; } server.configureBlocking(false); //3. Choose one reactor to handle NIO event selectorManager.getReactor(0).registerChannel(server, interestKey); System.out.println("INFO: NAMI Server started on port " + String.valueOf(port) + "..."); }
Example 2
Source File: NIOAcceptor.java From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License | 6 votes |
public NIOAcceptor(String name, String bindIp, int port, ConnectionFactory factory, NIOReactorPool reactorPool) throws IOException { super.setName(name); this.port = port; this.selector = Selector.open(); this.serverChannel = ServerSocketChannel.open(); this.serverChannel.configureBlocking(false); // recv buf this.serverChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true); this.serverChannel.setOption(StandardSocketOptions.SO_RCVBUF, 1024 * 32); // 32K // backlog=2048 this.serverChannel.bind(new InetSocketAddress(bindIp, port), 2048); this.serverChannel.register(selector, SelectionKey.OP_ACCEPT); this.factory = factory; this.reactorPool = reactorPool; }
Example 3
Source File: KeepAliveSockets.java From dragonwell8_jdk with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws Exception { boolean keepAlive = false; String prop = System.getProperty("com.sun.CORBA.transport.enableTcpKeepAlive"); if (prop != null) keepAlive = !"false".equalsIgnoreCase(prop); DefaultSocketFactoryImpl sfImpl = new DefaultSocketFactoryImpl(); ORBImpl orb = new ORBImpl(); orb.set_parameters(null); sfImpl.setORB(orb); ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(0)); InetSocketAddress isa = new InetSocketAddress("localhost", ssc.socket().getLocalPort()); Socket s = sfImpl.createSocket("ignore", isa); System.out.println("Received factory socket" + s); if (keepAlive != s.getKeepAlive()) throw new RuntimeException("KeepAlive value not honoured in CORBA socket"); }
Example 4
Source File: Debugger.java From javaide with GNU General Public License v3.0 | 6 votes |
/** * Create a new Debugger object, configured to listen for connections * on a specific port. */ Debugger(Client client, int listenPort) throws IOException { mClient = client; mListenPort = listenPort; mListenChannel = ServerSocketChannel.open(); mListenChannel.configureBlocking(false); // required for Selector InetSocketAddress addr = new InetSocketAddress( InetAddress.getByName("localhost"), //$NON-NLS-1$ listenPort); mListenChannel.socket().setReuseAddress(true); // enable SO_REUSEADDR mListenChannel.socket().bind(addr); mReadBuffer = ByteBuffer.allocate(INITIAL_BUF_SIZE); mPreDataBuffer = ByteBuffer.allocate(PRE_DATA_BUF_SIZE); mConnState = ST_NOT_CONNECTED; Log.d("ddms", "Created: " + this.toString()); }
Example 5
Source File: TCPThreadProxy.java From loom-fiber with MIT License | 6 votes |
@SuppressWarnings("resource") public static void main(String[] args) throws IOException { var server = ServerSocketChannel.open(); server.bind(new InetSocketAddress(7777)); System.out.println("server bound to " + server.getLocalAddress()); var remote = SocketChannel.open(); remote.connect(new InetSocketAddress(InetAddress.getByName(Host.NAME), 7)); //remote.configureBlocking(false); System.out.println("accepting ..."); var client = server.accept(); //client.configureBlocking(false); new Thread(runnable(client, remote)).start(); new Thread(runnable(remote, client)).start(); }
Example 6
Source File: AddressInUseTest.java From sctp with GNU Affero General Public License v3.0 | 5 votes |
private void doInitSocketServerTcp() throws IOException { dirtyServerTcp = ServerSocketChannel.open(); dirtyServerTcp.configureBlocking(false); // Bind the server socket to the specified address and port InetSocketAddress isa = new InetSocketAddress(CLIENT_HOST, CLIENT_PORT); dirtyServerTcp.bind(isa); }
Example 7
Source File: TcpProxyServer.java From VpnProxy with MIT License | 5 votes |
public TcpProxyServer(int port) throws IOException { m_Selector = Selector.open(); m_ServerSocketChannel = ServerSocketChannel.open(); m_ServerSocketChannel.configureBlocking(false); m_ServerSocketChannel.socket().bind(new InetSocketAddress(port)); m_ServerSocketChannel.register(m_Selector, SelectionKey.OP_ACCEPT); this.Port = (short) m_ServerSocketChannel.socket().getLocalPort(); Log.d(Constant.TAG, "AsyncTcpServer listen on " + (this.Port & 0xFFFF)); }
Example 8
Source File: SendUrgentData.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 5 votes |
private ServerSocketChannelThread(String name) { super(name); try { ssc = ServerSocketChannel.open(); ssc.bind(new InetSocketAddress((0))); } catch (IOException ex) { throw new RuntimeException(ex); } }
Example 9
Source File: ConnectionListener.java From tribaltrouble with GNU General Public License v2.0 | 5 votes |
private final static SelectionKey createServerSocket(NetworkSelector network, InetAddress ip, int port) throws IOException { ServerSocketChannel server_channel = ServerSocketChannel.open(); server_channel.configureBlocking(false); SocketAddress address = new InetSocketAddress(ip, port); server_channel.socket().setReuseAddress(true); server_channel.socket().bind(address); SelectionKey key = server_channel.register(network.getSelector(), SelectionKey.OP_ACCEPT); return key; }
Example 10
Source File: ConnectionHandler.java From joal with Apache License 2.0 | 5 votes |
@VisibleForTesting ServerSocketChannel bindToPort() throws IOException { // Bind to the first available port in the range ServerSocketChannel channel = null; for (int port = ConnectionHandler.PORT_RANGE_START; port <= ConnectionHandler.PORT_RANGE_END; port++) { final InetSocketAddress tryAddress = new InetSocketAddress(port); try { channel = ServerSocketChannel.open(); channel.socket().bind(tryAddress); channel.configureBlocking(false); break; } catch (final IOException ioe) { // Ignore, try next port logger.warn("Could not bind to port {}: {}, trying next port...", tryAddress.getPort(), ioe.getMessage()); try { if (channel != null) channel.close(); } catch (final IOException ignored) { } } } if (channel == null || !channel.socket().isBound()) { throw new IOException("No available port for the BitTorrent client!"); } return channel; }
Example 11
Source File: NioTcpAcceptor.java From craft-atom with MIT License | 5 votes |
@Override protected void bindByProtocol(SocketAddress address) throws IOException { ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.configureBlocking(false); ServerSocket ss = ssc.socket(); ss.setReuseAddress(config.isReuseAddress()); ss.bind(address, config.getBacklog()); ssc.register(selector, SelectionKey.OP_ACCEPT); boundmap.put(address, ssc); }
Example 12
Source File: Server.java From coding-snippets with MIT License | 5 votes |
private static void listenAndPush(int port) throws IOException, InterruptedException { try (ServerSocketChannel serverSocket = ServerSocketChannel.open()) { serverSocket.bind(new InetSocketAddress(port)); logger.info("Listening: %s", serverSocket); try (SocketChannel socket = serverSocket.accept()) { logger.info("Client connected: %s", socket); socket.configureBlocking(false); solution.outputResult(socket); } } }
Example 13
Source File: ServerSocketChannelTest.java From j2objc with Apache License 2.0 | 5 votes |
public void test_bind_failure() throws Exception { ServerSocketChannel portHog = ServerSocketChannel.open(); portHog.socket().bind(null); ServerSocketChannel ssc = ServerSocketChannel.open(); try { // Bind to a local address that is in use ssc.socket().bind(portHog.socket().getLocalSocketAddress()); fail(); } catch (IOException expected) { } finally { ssc.close(); portHog.close(); } }
Example 14
Source File: RDMAvsTcpBenchmarkServer.java From disni with Apache License 2.0 | 5 votes |
public void launch(String[] args) throws Exception { RdmaBenchmarkCmdLine cmdLine = new RdmaBenchmarkCmdLine("RDMAvsTcpBenchmarkServer"); try { cmdLine.parse(args); } catch (ParseException e) { cmdLine.printHelp(); System.exit(-1); } String host = cmdLine.getIp(); Integer port = cmdLine.getPort(); System.out.println("Address: " + host + ":" + port); InetAddress ipAddress = InetAddress.getByName(host); InetSocketAddress rdmaAddress = new InetSocketAddress(ipAddress, port); bufferSize = cmdLine.getSize(); System.out.println("Buffer size: " + bufferSize); loopCount = cmdLine.getLoop(); // Start RDMA Server //create a EndpointGroup. The RdmaActiveEndpointGroup contains CQ processing and delivers CQ event to the endpoint.dispatchCqEvent() method. endpointGroup = new RdmaActiveEndpointGroup<SendRecvServer.CustomServerEndpoint>(1000, false, 128, 4, 128); endpointGroup.init(this); //create a server endpoint serverEndpoint = endpointGroup.createServerEndpoint(); serverEndpoint.bind(rdmaAddress, 10); System.out.println("RdmaVsTcpBenchmarkServer bound to address " + rdmaAddress.toString()); // Start TCP Server InetSocketAddress tcpAddress = new InetSocketAddress(host, port + 1); serverSocket = ServerSocketChannel.open(); serverSocket.socket().bind(tcpAddress); serverSocket.socket().setReceiveBufferSize(bufferSize); System.out.println("TCP server listening " + tcpAddress); this.runRDMA(); this.runTCP(); System.exit(0); }
Example 15
Source File: HAService.java From rocketmq-all-4.1.0-incubating with Apache License 2.0 | 5 votes |
/** * Starts listening to slave connections. * * @throws Exception If fails. */ public void beginAccept() throws Exception { this.serverSocketChannel = ServerSocketChannel.open(); this.selector = RemotingUtil.openSelector(); this.serverSocketChannel.socket().setReuseAddress(true); this.serverSocketChannel.socket().bind(this.socketAddressListen); this.serverSocketChannel.configureBlocking(false); this.serverSocketChannel.register(this.selector, SelectionKey.OP_ACCEPT); }
Example 16
Source File: CloseAfterConnect.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(0)); InetAddress lh = InetAddress.getLocalHost(); final SocketChannel sc = SocketChannel.open(); final InetSocketAddress isa = new InetSocketAddress(lh, ssc.socket().getLocalPort()); // establish connection in another thread Runnable connector = new Runnable() { public void run() { try { sc.connect(isa); } catch (IOException ioe) { ioe.printStackTrace(); } } }; Thread thr = new Thread(connector); thr.start(); // wait for connect to be established and for thread to // terminate do { try { thr.join(); } catch (InterruptedException x) { } } while (thr.isAlive()); // check connection is established if (!sc.isConnected()) { throw new RuntimeException("SocketChannel not connected"); } // close channel - this triggered the bug as it attempted to signal // a thread that no longer exists sc.close(); // clean-up ssc.accept().close(); ssc.close(); }
Example 17
Source File: NioSslIntegrationTest.java From Chronicle-Network with Apache License 2.0 | 4 votes |
@Test public void shouldEncryptAndDecryptTraffic() throws Exception { final ExecutorService threadPool = Executors.newFixedThreadPool(2, new NamedThreadFactory("test")); final ServerSocketChannel serverChannel = ServerSocketChannel.open(); serverChannel.bind(new InetSocketAddress("0.0.0.0", 13337)); serverChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true); serverChannel.configureBlocking(true); final SocketChannel channel = SocketChannel.open(); channel.configureBlocking(false); channel.connect(new InetSocketAddress("127.0.0.1", serverChannel.socket().getLocalPort())); try { final Client client = new Client(channel); final StateMachineProcessor clientProcessor = new StateMachineProcessor(channel, false, SSLContextLoader.getInitialisedContext(), client); final SocketChannel serverConnection = serverChannel.accept(); serverConnection.configureBlocking(false); final Server server = new Server(serverConnection); final StateMachineProcessor serverProcessor = new StateMachineProcessor(serverConnection, true, SSLContextLoader.getInitialisedContext(), server); while (!(channel.finishConnect() && serverConnection.finishConnect())) { Thread.yield(); } if (SEND_DATA_BEFORE_SSL_HANDSHAKE) { testDataConnection(channel, serverConnection); } threadPool.submit(clientProcessor); threadPool.submit(serverProcessor); client.waitForResponse(10, TimeUnit.SECONDS); serverProcessor.stop(); clientProcessor.stop(); } finally { Closeable.closeQuietly(channel, serverChannel); } threadPool.shutdown(); assertTrue(threadPool.awaitTermination(10, TimeUnit.SECONDS)); }
Example 18
Source File: ActiveLookupProvider.java From bt with Apache License 2.0 | 4 votes |
public Server() throws IOException { chan = ServerSocketChannel.open(); chan.configureBlocking(false); chan.bind(new InetSocketAddress(InetAddress.getByAddress(new byte[16]), 36578)); }
Example 19
Source File: LotsOfCancels.java From TencentKona-8 with GNU General Public License v2.0 | 4 votes |
static void runTest(int initCount, int massCount, int maxSelectTime) throws Exception { testStartTime = System.nanoTime(); InetSocketAddress address = new InetSocketAddress("127.0.0.1", 7359); // Create server channel, add it to selector and run epoll_ctl. log("Setting up server"); Selector serverSelector = Selector.open(); ServerSocketChannel server = ServerSocketChannel.open(); server.configureBlocking(false); server.socket().bind(address, 5000); server.register(serverSelector, SelectionKey.OP_ACCEPT); serverSelector.selectNow(); log("Setting up client"); ClientThread client = new ClientThread(address); client.start(); Thread.sleep(100); // Set up initial set of client sockets. log("Starting initial client connections"); client.connectClients(initCount); Thread.sleep(500); // Wait for client connections to arrive // Accept all initial client sockets, add to selector and run // epoll_ctl. log("Accepting initial connections"); List<SocketChannel> serverChannels1 = acceptAndAddAll(serverSelector, server, initCount); if (serverChannels1.size() != initCount) { throw new Exception("Accepted " + serverChannels1.size() + " instead of " + initCount); } serverSelector.selectNow(); // Set up mass set of client sockets. log("Requesting mass client connections"); client.connectClients(massCount); Thread.sleep(500); // Wait for client connections to arrive // Accept all mass client sockets, add to selector and do NOT // run epoll_ctl. log("Accepting mass connections"); List<SocketChannel> serverChannels2 = acceptAndAddAll(serverSelector, server, massCount); if (serverChannels2.size() != massCount) { throw new Exception("Accepted " + serverChannels2.size() + " instead of " + massCount); } // Close initial set of sockets. log("Closing initial connections"); closeAll(serverChannels1); // Now get the timing of select() call. log("Running the final select call"); long startTime = System.nanoTime(); serverSelector.selectNow(); long duration = durationMillis(startTime); log("Init count = " + initCount + ", mass count = " + massCount + ", duration = " + duration + "ms"); if (duration > maxSelectTime) { System.out.println ("\n\n\n\n\nFAILURE: The final selectNow() took " + duration + "ms " + "- seems like O(N^2) bug is still here\n\n"); System.exit(1); } }
Example 20
Source File: SocketCreator.java From gemfirexd-oss with Apache License 2.0 | 4 votes |
/** * Creates or bind server socket to a random port selected * from tcp-port-range which is same as membership-port-range. * @param ba * @param backlog * @param isBindAddress * @param logger * @param tcpBufferSize * @return Returns the new server socket. * @throws IOException */ public ServerSocket createServerSocketUsingPortRange(InetAddress ba, int backlog, boolean isBindAddress, boolean useNIO, GFLogWriter logger, int tcpBufferSize, int[] tcpPortRange) 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 = SocketCreator.getDefaultInstance().createServerSocket(localPort, backlog, isBindAddress? ba : null, logger, tcpBufferSize); } break; } catch (java.net.SocketException ex) { if (useNIO || SocketCreator.treatAsBindException(ex)) { localPort++; } else { throw ex; } } } return socket; }