Java Code Examples for java.nio.channels.ServerSocketChannel#accept()

The following examples show how to use java.nio.channels.ServerSocketChannel#accept() . 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: SocketChannelTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * @tests SocketChannel#read(ByteBuffer[], int, int) with a null ByteBuffer
 */
public void test_socketChannel_read_ByteBufferII_bufNULL() throws Exception {
    // regression 3 for HARMONY-549
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.socket().bind(null);
    SocketChannel sc = SocketChannel.open();
    sc.connect(ssc.socket().getLocalSocketAddress());
    ssc.accept();
    ByteBuffer[] buf = new ByteBuffer[2];
    buf[0] = ByteBuffer.allocate(1);
    // let buf[1] be null
    try {
        sc.read(buf, 0, 2);
        fail("should throw NullPointerException");
    } catch (NullPointerException expected) {
    }
    ssc.close();
    sc.close();
}
 
Example 2
Source File: NonBlockingServerWithOffLoopTasks.java    From tls-channel with MIT License 6 votes vote down vote up
private static void handleNewConnection(
    SSLContext sslContext, Selector selector, ServerSocketChannel serverChannel)
    throws IOException {
  // accept new connection
  SocketChannel rawChannel = serverChannel.accept();
  rawChannel.configureBlocking(false);

  // wrap raw channel in TlsChannel
  TlsChannel tlsChannel =
      ServerTlsChannel.newBuilder(rawChannel, sslContext).withRunTasks(false).build();

  /*
   * Wrap raw channel with a TlsChannel. Note that the raw channel is registered in the selector
   * and the TlsChannel put as an attachment register the channel for reading, because TLS
   * connections are initiated by clients.
   */
  SelectionKey newKey = rawChannel.register(selector, SelectionKey.OP_READ);
  newKey.attach(tlsChannel);
}
 
Example 3
Source File: SocketChannelTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * @tests SocketChannel#write(ByteBuffer[], int, int)
 */
public void test_socketChannel_write_ByteBufferII() throws Exception {
    // regression 2 for HARMONY-549
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.socket().bind(null);
    SocketChannel sc = SocketChannel.open();
    sc.connect(ssc.socket().getLocalSocketAddress());
    SocketChannel sock = ssc.accept();
    ByteBuffer[] buf = { ByteBuffer.allocate(10), null };
    try {
        sc.write(buf, 0, 2);
        fail("should throw NPE");
    } catch (NullPointerException expected) {
    }
    ssc.close();
    sc.close();
    ByteBuffer target = ByteBuffer.allocate(10);
    assertEquals(-1, sock.read(target));
}
 
Example 4
Source File: SingleSocketTcpWriterTest.java    From kieker with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldConnectWithDefault() throws Exception {
	final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
	try {
		serverSocketChannel.bind(new InetSocketAddress(HOSTNAME, PORT));
		serverSocketChannel.configureBlocking(false);
		serverSocketChannel.accept(); // non-blocking accept

		final SingleSocketTcpWriter writer = new SingleSocketTcpWriter(this.configuration);
		try {
			writer.onStarting();
		} finally {
			writer.onTerminating();
		}
	} finally {
		serverSocketChannel.close();
	}

	Assert.assertTrue(true); // NOPMD (this test should not throw any exception)
}
 
Example 5
Source File: SelectorThread.java    From L2jBrasil with GNU General Public License v3.0 6 votes vote down vote up
private final void acceptConnection(final SelectionKey key, MMOConnection<T> con)
{
    ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
    SocketChannel sc;

    try
    {
        while ((sc = ssc.accept()) != null)
        {
            if (_acceptFilter == null || _acceptFilter.accept(sc))
            {
                sc.configureBlocking(false);
                SelectionKey clientKey = sc.register(_selector, SelectionKey.OP_READ);
                con = new MMOConnection<T>(this, sc.socket(), clientKey);
                con.setClient(_clientFactory.create(con));
                clientKey.attach(con);
            }
            else
                sc.socket().close();
        }
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}
 
Example 6
Source File: NioEchoServer.java    From JavaTutorial with Apache License 2.0 6 votes vote down vote up
/**
 * 接受新的Socket连接。
 * 
 * @param selector 选择器
 * @param selectionKey 
 * @return
 * @throws IOException
 * @throws ClosedChannelException
 */
private static SocketChannel acceptNew(Selector selector,
        SelectionKey selectionKey) throws IOException,
        ClosedChannelException {
    ServerSocketChannel server = (ServerSocketChannel) selectionKey.channel();
    SocketChannel socketChannel = server.accept();
    if (null != socketChannel) {
        if (logger.isLoggable(Level.INFO)) {
            logger.info("收到一个新的连接,客户端IP:"+socketChannel.socket().getInetAddress().getHostAddress()+",客户端Port:"+socketChannel.socket().getPort());
        }
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);
    }
    
    return socketChannel;
}
 
Example 7
Source File: SocketProxyTest.java    From rxmqtt with Apache License 2.0 5 votes vote down vote up
protected void connectClientToRemote(Selector selector, Selector remoteSelector, 
        ServerSocketChannel serverSocket)
  throws IOException {
    
    logger.info("Proxy registering client.");

    final SocketChannel client = serverSocket.accept();
    client.configureBlocking(false);
    client.finishConnect();
    logger.info("Proxy registered client: " + client.socket().getRemoteSocketAddress().toString());    
    
    try {
        logger.info("Proxy opening remote address: " + this.remoteAddress);
        final SocketChannel remote = SocketChannel.open(this.remoteAddress);
        remote.configureBlocking(false);
        remote.finishConnect();
        remote.register(remoteSelector, SelectionKey.OP_READ);
        proxy.put(client, remote);    
        logger.info("Proxy opened remote address.");
    } catch (IOException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        client.close();
        throw e;
    }
    
    client.register(selector, SelectionKey.OP_READ);
}
 
Example 8
Source File: SelectorThread.java    From sctp with GNU Affero General Public License v3.0 5 votes vote down vote up
private void acceptTcp(SelectionKey key) throws IOException {
	
	// For an accept to be pending the channel must be a server socket
	// channel.
	ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();

	// Accept the connection and make it non-blocking
	SocketChannel socketChannel = serverSocketChannel.accept();

	Set<SocketAddress> peerAddresses = new HashSet<SocketAddress>();
	peerAddresses.add(socketChannel.getRemoteAddress());

	this.doAccept(serverSocketChannel, socketChannel, peerAddresses);
}
 
Example 9
Source File: TestBlockingNIO.java    From cs-summary-reflection with Apache License 2.0 5 votes vote down vote up
@Test
public void server() throws IOException {
    // 1. 获取通道
    ServerSocketChannel ssChannel = ServerSocketChannel.open();

    FileChannel outChannel =
            FileChannel.open(
                    Paths.get("2.jpg"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);

    // 2. 绑定连接
    ssChannel.bind(new InetSocketAddress(9898));

    // 3. 获取客户端连接的通道
    SocketChannel sChannel = ssChannel.accept();

    // 4. 分配指定大小的缓冲区
    ByteBuffer buf = ByteBuffer.allocate(1024);

    // 5. 接收客户端的数据,并保存到本地
    while (sChannel.read(buf) != -1) {
        buf.flip();
        outChannel.write(buf);
        buf.clear();
    }

    // 6. 关闭通道
    sChannel.close();
    outChannel.close();
    ssChannel.close();
}
 
Example 10
Source File: Transfer.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void xferTest07() throws Exception { // for bug 5103988
    File source = File.createTempFile("source", null);
    source.deleteOnExit();

    FileChannel sourceChannel = new RandomAccessFile(source, "rw")
        .getChannel();
    sourceChannel.position(32000L)
        .write(ByteBuffer.wrap("The End".getBytes()));

    // The sink is a non-blocking socket channel
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.socket().bind(new InetSocketAddress(0));
    InetSocketAddress sa = new InetSocketAddress(
        InetAddress.getLocalHost(), ssc.socket().getLocalPort());
    SocketChannel sink = SocketChannel.open(sa);
    sink.configureBlocking(false);
    SocketChannel other = ssc.accept();

    long size = sourceChannel.size();

    // keep sending until congested
    long n;
    do {
        n = sourceChannel.transferTo(0, size, sink);
    } while (n > 0);

    sourceChannel.close();
    sink.close();
    other.close();
    ssc.close();
    source.delete();
}
 
Example 11
Source File: SocketServer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void acceptConnection( SelectionKey key ) throws IOException {
    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();

    SocketChannel socketChannel = serverSocketChannel.accept();
    socketChannel.configureBlocking(false);
    socketChannel.register(getSelector(), SelectionKey.OP_READ);
    initWriteQueue( socketChannel.keyFor(getSelector()));
}
 
Example 12
Source File: AsynchronousEcho.java    From vertx-in-action with MIT License 5 votes vote down vote up
private static void newConnection(Selector selector, SelectionKey key) throws IOException {
  ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
  SocketChannel socketChannel = serverSocketChannel.accept();
  socketChannel
    .configureBlocking(false)
    .register(selector, SelectionKey.OP_READ);
  contexts.put(socketChannel, new Context());
}
 
Example 13
Source File: ServerSocket.java    From chuidiang-ejemplos with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
   ServerSocketChannel server = ServerSocketChannel.open();
   server.bind(new InetSocketAddress("127.0.0.1", 5557));
   while (true) {
      SocketChannel client = server.accept();
      new Thread(new Client(client)).start();
   }
}
 
Example 14
Source File: RacyDeregister.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    InetAddress addr = InetAddress.getByName(null);
    ServerSocketChannel sc = ServerSocketChannel.open();
    sc.socket().bind(new InetSocketAddress(addr, 0));

    SocketChannel.open(new InetSocketAddress(addr,
            sc.socket().getLocalPort()));

    SocketChannel accepted = sc.accept();
    accepted.configureBlocking(false);

    SocketChannel.open(new InetSocketAddress(addr,
            sc.socket().getLocalPort()));
    SocketChannel accepted2 = sc.accept();
    accepted2.configureBlocking(false);

    final Selector sel = Selector.open();
    SelectionKey key2 = accepted2.register(sel, SelectionKey.OP_READ);
    final SelectionKey[] key = new SelectionKey[]{
        accepted.register(sel, SelectionKey.OP_READ)};


    // thread that will be changing key[0].interestOps to OP_READ | OP_WRITE
    new Thread() {

        public void run() {
            try {
                for (int k = 0; k < 15; k++) {
                    for (int i = 0; i < 10000; i++) {
                        synchronized (notifyLock) {
                            synchronized (selectorLock) {
                                sel.wakeup();
                                key[0].interestOps(SelectionKey.OP_READ
                                        | SelectionKey.OP_WRITE);
                            }
                            notified = false;
                            long beginTime = System.currentTimeMillis();
                            while (true) {
                                notifyLock.wait(5000);
                                if (notified) {
                                    break;
                                }
                                long endTime = System.currentTimeMillis();
                                if (endTime - beginTime > 5000) {
                                    succTermination = false;
                                    // wake up main thread doing select()
                                    sel.wakeup();
                                    return;
                                }
                            }
                        }
                    }
                }
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            } catch (Exception e) {
                System.out.println(e);
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            }
        }
    }.start();

    // main thread will be doing registering/deregistering with the sel
    while (true) {
        sel.select();
        if (Boolean.TRUE.equals(succTermination)) {
            System.out.println("Test passed");
            sel.close();
            sc.close();
            break;
        } else if (Boolean.FALSE.equals(succTermination)) {
            System.out.println("Failed to pass the test");
            sel.close();
            sc.close();
            throw new RuntimeException("Failed to pass the test");
        }
        synchronized (selectorLock) {
        }
        if (sel.selectedKeys().contains(key[0]) && key[0].isWritable()) {
            synchronized (notifyLock) {
                notified = true;
                notifyLock.notify();
                key[0].cancel();
                sel.selectNow();
                key2 = accepted2.register(sel, SelectionKey.OP_READ);
                key[0] = accepted.register(sel, SelectionKey.OP_READ);
            }
        }
        key2.cancel();
        sel.selectedKeys().clear();
    }
}
 
Example 15
Source File: NioSslIntegrationTest.java    From Chronicle-Network with Apache License 2.0 4 votes vote down vote up
@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 16
Source File: RacyDeregister.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    InetAddress addr = InetAddress.getByName(null);
    ServerSocketChannel sc = ServerSocketChannel.open();
    sc.socket().bind(new InetSocketAddress(addr, 0));

    SocketChannel.open(new InetSocketAddress(addr,
            sc.socket().getLocalPort()));

    SocketChannel accepted = sc.accept();
    accepted.configureBlocking(false);

    SocketChannel.open(new InetSocketAddress(addr,
            sc.socket().getLocalPort()));
    SocketChannel accepted2 = sc.accept();
    accepted2.configureBlocking(false);

    final Selector sel = Selector.open();
    SelectionKey key2 = accepted2.register(sel, SelectionKey.OP_READ);
    final SelectionKey[] key = new SelectionKey[]{
        accepted.register(sel, SelectionKey.OP_READ)};


    // thread that will be changing key[0].interestOps to OP_READ | OP_WRITE
    new Thread() {

        public void run() {
            try {
                for (int k = 0; k < 15; k++) {
                    for (int i = 0; i < 10000; i++) {
                        synchronized (notifyLock) {
                            synchronized (selectorLock) {
                                sel.wakeup();
                                key[0].interestOps(SelectionKey.OP_READ
                                        | SelectionKey.OP_WRITE);
                            }
                            notified = false;
                            long beginTime = System.currentTimeMillis();
                            while (true) {
                                notifyLock.wait(5000);
                                if (notified) {
                                    break;
                                }
                                long endTime = System.currentTimeMillis();
                                if (endTime - beginTime > 5000) {
                                    succTermination = false;
                                    // wake up main thread doing select()
                                    sel.wakeup();
                                    return;
                                }
                            }
                        }
                    }
                }
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            } catch (Exception e) {
                System.out.println(e);
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            }
        }
    }.start();

    // main thread will be doing registering/deregistering with the sel
    while (true) {
        sel.select();
        if (Boolean.TRUE.equals(succTermination)) {
            System.out.println("Test passed");
            sel.close();
            sc.close();
            break;
        } else if (Boolean.FALSE.equals(succTermination)) {
            System.out.println("Failed to pass the test");
            sel.close();
            sc.close();
            throw new RuntimeException("Failed to pass the test");
        }
        synchronized (selectorLock) {
        }
        if (sel.selectedKeys().contains(key[0]) && key[0].isWritable()) {
            synchronized (notifyLock) {
                notified = true;
                notifyLock.notify();
                key[0].cancel();
                sel.selectNow();
                key2 = accepted2.register(sel, SelectionKey.OP_READ);
                key[0] = accepted.register(sel, SelectionKey.OP_READ);
            }
        }
        key2.cancel();
        sel.selectedKeys().clear();
    }
}
 
Example 17
Source File: HAReceiveService.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
         * Gets the client connection and open the channel in a non-blocking
         * mode so we will read whatever is available and loop until all data
         * has been read.
         */
        public Client(//
                final ServerSocketChannel server //
//                , final HASendService downstream //
//                , final InetSocketAddress addrNext//
        ) throws IOException {

            try {
                
                /*
                 * Note: This binds a port for a specific upstream HASendService
                 * that will be talking to this HAReceiveService.
                 */
                client = server.accept();
                client.configureBlocking(false);
                if (!client.finishConnect())
                    throw new IOException("Upstream client not connected");
                
                clientSelector = Selector.open();

                // must register OP_READ selector on the new client
                clientKey = client.register(clientSelector,
                        SelectionKey.OP_READ);
                
                if (log.isInfoEnabled())
                    log.info("Accepted new connection");
                
//                this.downstream = downstream;
//                
//                // Prepare downstream (if any) for incremental transfers
//                if (addrNext != null) {
//
//                    downstream.start(addrNext);
//                    
//                }

            } catch (IOException ex) {
                
                close();

                throw ex;
                
            }
            
        }
 
Example 18
Source File: RacyDeregister.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    InetAddress addr = InetAddress.getByName(null);
    ServerSocketChannel sc = ServerSocketChannel.open();
    sc.socket().bind(new InetSocketAddress(addr, 0));

    SocketChannel.open(new InetSocketAddress(addr,
            sc.socket().getLocalPort()));

    SocketChannel accepted = sc.accept();
    accepted.configureBlocking(false);

    SocketChannel.open(new InetSocketAddress(addr,
            sc.socket().getLocalPort()));
    SocketChannel accepted2 = sc.accept();
    accepted2.configureBlocking(false);

    final Selector sel = Selector.open();
    SelectionKey key2 = accepted2.register(sel, SelectionKey.OP_READ);
    final SelectionKey[] key = new SelectionKey[]{
        accepted.register(sel, SelectionKey.OP_READ)};


    // thread that will be changing key[0].interestOps to OP_READ | OP_WRITE
    new Thread() {

        public void run() {
            try {
                for (int k = 0; k < 15; k++) {
                    for (int i = 0; i < 10000; i++) {
                        synchronized (notifyLock) {
                            synchronized (selectorLock) {
                                sel.wakeup();
                                key[0].interestOps(SelectionKey.OP_READ
                                        | SelectionKey.OP_WRITE);
                            }
                            notified = false;
                            long beginTime = System.currentTimeMillis();
                            while (true) {
                                notifyLock.wait(5000);
                                if (notified) {
                                    break;
                                }
                                long endTime = System.currentTimeMillis();
                                if (endTime - beginTime > 5000) {
                                    succTermination = false;
                                    // wake up main thread doing select()
                                    sel.wakeup();
                                    return;
                                }
                            }
                        }
                    }
                }
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            } catch (Exception e) {
                System.out.println(e);
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            }
        }
    }.start();

    // main thread will be doing registering/deregistering with the sel
    while (true) {
        sel.select();
        if (Boolean.TRUE.equals(succTermination)) {
            System.out.println("Test passed");
            sel.close();
            sc.close();
            break;
        } else if (Boolean.FALSE.equals(succTermination)) {
            System.out.println("Failed to pass the test");
            sel.close();
            sc.close();
            throw new RuntimeException("Failed to pass the test");
        }
        synchronized (selectorLock) {
        }
        if (sel.selectedKeys().contains(key[0]) && key[0].isWritable()) {
            synchronized (notifyLock) {
                notified = true;
                notifyLock.notify();
                key[0].cancel();
                sel.selectNow();
                key2 = accepted2.register(sel, SelectionKey.OP_READ);
                key[0] = accepted.register(sel, SelectionKey.OP_READ);
            }
        }
        key2.cancel();
        sel.selectedKeys().clear();
    }
}
 
Example 19
Source File: Server.java    From learning-code with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException {
    final int port = 6789;
    // 1. 打开 ServerSocketChannel 用来监听客户端连接请求
    ServerSocketChannel channel = ServerSocketChannel.open();
    ServerSocket socket = channel.socket();
    socket.bind(new InetSocketAddress(port));
    // 2. 设置非祖塞模式
    channel.configureBlocking(false);
    Selector selector = Selector.open();
    // 3. 将 ServerSocketChannel 注册到 Selector 上,并且监听 ACCEPT 事件
    channel.register(selector, SelectionKey.OP_ACCEPT);

    // 缓冲区,设置大小 1M
    final ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
    while (true) {
        int select = selector.select();
        // 4. 判断是否就绪,如果什么消息也没有则什么也不做
        if (select == 0) {
            continue;
        }
        Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
        // 5. 如果有消息, 处理新的请求,
        while (iterator.hasNext()) {
            SelectionKey selectionKey = iterator.next();
            iterator.remove();
            if (!selectionKey.isValid()) {
                continue;
            }
            // 6. 判断是否有可以接受的连接,有的话创建连接
            if (selectionKey.isAcceptable()) {
                ServerSocketChannel acceptChannel = (ServerSocketChannel) selectionKey.channel();
                // 7. 创建客户端连接连接,并且设置非阻塞模式,将连接注册到 Selector 上,监听读操作,
                SocketChannel acceptSocket = acceptChannel.accept();
                acceptSocket.configureBlocking(false);
                acceptSocket.register(selector, SelectionKey.OP_READ);
            }
            // 8. 判断该消息是否可以读
            else if (selectionKey.isReadable()) {
                //9. 开始读取数据
                SocketChannel readChannel = (SocketChannel) selectionKey.channel();
                byteBuffer.clear();
                while (readChannel.read(byteBuffer) > 0) {
                    byteBuffer.flip();
                    while (byteBuffer.hasRemaining()) {
                        // 解码
                        byte[] bytes = new byte[byteBuffer.remaining()];
                        byteBuffer.get(bytes);
                        String message = new String(bytes, StandardCharsets.UTF_8);
                        System.out.println(message);
                    }
                }
                byteBuffer.clear();
            }
        }
    }
}
 
Example 20
Source File: ShellLaunchManager.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Registers the connection and initiates the listening socket.
 * @param project the project which is being run / debugged
 * @param debugger if true, the connection will pair with a debugger session.
 */
public ShellAgent openForProject(Project p, boolean debugger) throws IOException {
    ServerSocket ss;
    
    String encodedKey;
    boolean shouldInit = false;
    
    synchronized (this) {
        shouldInit = usedKeys.isEmpty();
        do {
            BigInteger key = BigInteger.probablePrime(64, keyGenerator);
            encodedKey = key.toString(Character.MAX_RADIX);
        } while (!usedKeys.add(encodedKey));
    }
    
    if (shouldInit) {
        init();
    }
    
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.configureBlocking(false);
    SocketAddress local = new InetSocketAddress(
        // PENDING: choose something better for remote debugging!
        InetAddress.getLoopbackAddress(),
        0);
    ssc.bind(local);
    ssc.accept();
    ss = ssc.socket();
    LOG.log(Level.FINE, "Creating new server socket {0} for project: {1}", new Object[] {
        ss, p
    });
    ShellAgent agent = new ShellAgent(this, p, ss, encodedKey, debugger);
    synchronized (this) {
        registeredAgents.put(encodedKey, agent);
    }
    synchronized (requests) {
        servers.wakeup();
        requests.add(agent);
        
    }
    return agent;
}