Search in sources :

Example 11 with AsynchronousServerSocketChannel

use of java.nio.channels.AsynchronousServerSocketChannel in project j2objc by google.

the class AsynchronousServerSocketChannelTest method test_completionHandlerAccept.

public void test_completionHandlerAccept() throws Throwable {
    AsynchronousServerSocketChannel assc = AsynchronousServerSocketChannel.open();
    assc.bind(new InetSocketAddress(0));
    FutureLikeCompletionHandler<AsynchronousSocketChannel> acceptCompletionHandler = new FutureLikeCompletionHandler<AsynchronousSocketChannel>();
    assc.accept(null, /* attachment */
    acceptCompletionHandler);
    Socket s = new Socket();
    s.connect(assc.getLocalAddress());
    AsynchronousSocketChannel asc = acceptCompletionHandler.get(1000);
    assertNotNull(asc);
    assertTrue(s.isConnected());
    assertNotNull(asc.getLocalAddress());
    assertEquals(asc.getLocalAddress(), s.getRemoteSocketAddress());
    assertNotNull(asc.getRemoteAddress());
    assertEquals(asc.getRemoteAddress(), s.getLocalSocketAddress());
    assertNull(acceptCompletionHandler.getAttachment());
    asc.close();
    s.close();
    assc.close();
}
Also used : AsynchronousSocketChannel(java.nio.channels.AsynchronousSocketChannel) InetSocketAddress(java.net.InetSocketAddress) AsynchronousServerSocketChannel(java.nio.channels.AsynchronousServerSocketChannel) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket)

Example 12 with AsynchronousServerSocketChannel

use of java.nio.channels.AsynchronousServerSocketChannel in project sts4 by spring-projects.

the class LaunguageServerApp method createSocketLauncher.

private <T> Launcher<T> createSocketLauncher(Object localService, Class<T> remoteInterface, SocketAddress socketAddress, ExecutorService executorService, Function<MessageConsumer, MessageConsumer> wrapper) throws IOException {
    AsynchronousServerSocketChannel serverSocket = AsynchronousServerSocketChannel.open().bind(socketAddress);
    AsynchronousSocketChannel socketChannel;
    try {
        socketChannel = serverSocket.accept().get();
        return Launcher.createIoLauncher(localService, remoteInterface, Channels.newInputStream(socketChannel), Channels.newOutputStream(socketChannel), executorService, wrapper);
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
    return null;
}
Also used : AsynchronousSocketChannel(java.nio.channels.AsynchronousSocketChannel) AsynchronousServerSocketChannel(java.nio.channels.AsynchronousServerSocketChannel) ExecutionException(java.util.concurrent.ExecutionException)

Example 13 with AsynchronousServerSocketChannel

use of java.nio.channels.AsynchronousServerSocketChannel in project jetty.project by eclipse.

the class IOTest method testAsyncSocketChannel.

@Test
public void testAsyncSocketChannel() throws Exception {
    AsynchronousServerSocketChannel connector = AsynchronousServerSocketChannel.open();
    connector.bind(null);
    InetSocketAddress addr = (InetSocketAddress) connector.getLocalAddress();
    Future<AsynchronousSocketChannel> acceptor = connector.accept();
    AsynchronousSocketChannel client = AsynchronousSocketChannel.open();
    client.connect(new InetSocketAddress("127.0.0.1", addr.getPort())).get(5, TimeUnit.SECONDS);
    AsynchronousSocketChannel server = acceptor.get(5, TimeUnit.SECONDS);
    ByteBuffer read = ByteBuffer.allocate(1024);
    Future<Integer> reading = server.read(read);
    byte[] data = "Testing 1 2 3".getBytes(StandardCharsets.UTF_8);
    ByteBuffer write = BufferUtil.toBuffer(data);
    Future<Integer> writing = client.write(write);
    writing.get(5, TimeUnit.SECONDS);
    reading.get(5, TimeUnit.SECONDS);
    read.flip();
    Assert.assertEquals(ByteBuffer.wrap(data), read);
}
Also used : AsynchronousSocketChannel(java.nio.channels.AsynchronousSocketChannel) InetSocketAddress(java.net.InetSocketAddress) AsynchronousServerSocketChannel(java.nio.channels.AsynchronousServerSocketChannel) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.Test)

Example 14 with AsynchronousServerSocketChannel

use of java.nio.channels.AsynchronousServerSocketChannel in project elasticsearch by elastic.

the class ExampleTestFixture method main.

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        throw new IllegalArgumentException("ExampleTestFixture <logDirectory>");
    }
    Path dir = Paths.get(args[0]);
    AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
    // write pid file
    Path tmp = Files.createTempFile(dir, null, null);
    String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
    Files.write(tmp, Collections.singleton(pid));
    Files.move(tmp, dir.resolve("pid"), StandardCopyOption.ATOMIC_MOVE);
    // write port file
    tmp = Files.createTempFile(dir, null, null);
    InetSocketAddress bound = (InetSocketAddress) server.getLocalAddress();
    if (bound.getAddress() instanceof Inet6Address) {
        Files.write(tmp, Collections.singleton("[" + bound.getHostString() + "]:" + bound.getPort()));
    } else {
        Files.write(tmp, Collections.singleton(bound.getHostString() + ":" + bound.getPort()));
    }
    Files.move(tmp, dir.resolve("ports"), StandardCopyOption.ATOMIC_MOVE);
    // go time
    server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {

        @Override
        public void completed(AsynchronousSocketChannel socket, Void attachment) {
            server.accept(null, this);
            try (AsynchronousSocketChannel ch = socket) {
                ch.write(ByteBuffer.wrap("TEST\n".getBytes(StandardCharsets.UTF_8))).get();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public void failed(Throwable exc, Void attachment) {
        }
    });
    // wait forever, until you kill me
    Thread.sleep(Long.MAX_VALUE);
}
Also used : Path(java.nio.file.Path) InetSocketAddress(java.net.InetSocketAddress) AsynchronousServerSocketChannel(java.nio.channels.AsynchronousServerSocketChannel) Inet6Address(java.net.Inet6Address) AsynchronousSocketChannel(java.nio.channels.AsynchronousSocketChannel)

Example 15 with AsynchronousServerSocketChannel

use of java.nio.channels.AsynchronousServerSocketChannel in project baseio by generallycloud.

the class AioServerDemo method main.

public static void main(String[] args) throws Exception {
    AsynchronousChannelGroup group = AsynchronousChannelGroup.withThreadPool(Executors.newFixedThreadPool(4));
    AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open(group).bind(new InetSocketAddress("0.0.0.0", 8013));
    server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {

        @Override
        public void completed(AsynchronousSocketChannel result, Void attachment) {
            // 接受下一个连接
            server.accept(null, this);
            try {
                ByteBuffer readBuffer = ByteBuffer.allocate(999);
                result.read(readBuffer);
                String now = new Date().toString();
                ByteBuffer buffer = encoder.encode(CharBuffer.wrap(now + "\r\n"));
                // result.write(buffer, null, new
                // CompletionHandler<Integer,Void>(){...}); //callback
                // or
                Future<Integer> f = result.write(buffer);
                f.get();
                System.out.println("sent to client: " + now);
                result.close();
            } catch (IOException | InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void failed(Throwable exc, Void attachment) {
            exc.printStackTrace();
        }
    });
    ThreadUtil.sleep(9999999);
    group.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
}
Also used : AsynchronousSocketChannel(java.nio.channels.AsynchronousSocketChannel) InetSocketAddress(java.net.InetSocketAddress) AsynchronousChannelGroup(java.nio.channels.AsynchronousChannelGroup) AsynchronousServerSocketChannel(java.nio.channels.AsynchronousServerSocketChannel) Future(java.util.concurrent.Future) ByteBuffer(java.nio.ByteBuffer) Date(java.util.Date)

Aggregations

AsynchronousServerSocketChannel (java.nio.channels.AsynchronousServerSocketChannel)21 InetSocketAddress (java.net.InetSocketAddress)15 AsynchronousSocketChannel (java.nio.channels.AsynchronousSocketChannel)12 AlreadyBoundException (java.nio.channels.AlreadyBoundException)4 ExecutionException (java.util.concurrent.ExecutionException)4 ServerSocket (java.net.ServerSocket)3 Socket (java.net.Socket)3 ClosedChannelException (java.nio.channels.ClosedChannelException)3 NotYetBoundException (java.nio.channels.NotYetBoundException)3 UnresolvedAddressException (java.nio.channels.UnresolvedAddressException)3 IOException (java.io.IOException)2 BindException (java.net.BindException)2 ByteBuffer (java.nio.ByteBuffer)2 AsynchronousChannelGroup (java.nio.channels.AsynchronousChannelGroup)2 AsynchronousCloseException (java.nio.channels.AsynchronousCloseException)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 Inet6Address (java.net.Inet6Address)1 SocketOption (java.net.SocketOption)1 AsynchronousChannelProvider (java.nio.channels.spi.AsynchronousChannelProvider)1 Path (java.nio.file.Path)1