public void start() {
    final Xnio xnio;
    try {
      // Do what org.jboss.as.remoting.XnioUtil does
      xnio =
          Xnio.getInstance(
              null,
              Module.getModuleFromCallerModuleLoader(
                      ModuleIdentifier.fromString("org.jboss.xnio.nio"))
                  .getClassLoader());
    } catch (Exception e) {
      throw new IllegalStateException(e.getLocalizedMessage());
    }
    try {
      // TODO make this configurable
      worker =
          xnio.createWorker(
              OptionMap.builder()
                  .set(Options.WORKER_IO_THREADS, 4)
                  .set(Options.CONNECTION_HIGH_WATER, 1000000)
                  .set(Options.CONNECTION_LOW_WATER, 1000000)
                  .set(Options.WORKER_TASK_CORE_THREADS, 10)
                  .set(Options.WORKER_TASK_MAX_THREADS, 12)
                  .set(Options.TCP_NODELAY, true)
                  .set(Options.CORK, true)
                  .getMap());

      Builder serverOptionsBuilder =
          OptionMap.builder().set(Options.TCP_NODELAY, true).set(Options.REUSE_ADDRESSES, true);
      ChannelListener acceptListener = ChannelListeners.openListenerAdapter(openListener);
      if (httpAddress != null) {
        normalServer =
            worker.createStreamConnectionServer(
                httpAddress, acceptListener, serverOptionsBuilder.getMap());
        normalServer.resumeAccepts();
      }
      if (secureAddress != null) {
        SSLContext sslContext = securityRealm.getSSLContext();
        Set<AuthMechanism> supportedMechanisms =
            securityRealm.getSupportedAuthenticationMechanisms();
        if (supportedMechanisms.contains(AuthMechanism.CLIENT_CERT)) {
          if (supportedMechanisms.contains(AuthMechanism.DIGEST)
              || supportedMechanisms.contains(AuthMechanism.PLAIN)) {
            // Username / Password auth is possible so don't mandate a client certificate.
            serverOptionsBuilder.set(SSL_CLIENT_AUTH_MODE, REQUESTED);
          } else {
            serverOptionsBuilder.set(SSL_CLIENT_AUTH_MODE, REQUIRED);
          }
        }
        OptionMap secureOptions = serverOptionsBuilder.getMap();
        XnioSsl xnioSsl = new JsseXnioSsl(worker.getXnio(), secureOptions, sslContext);
        secureServer =
            xnioSsl.createSslConnectionServer(worker, secureAddress, acceptListener, secureOptions);
        secureServer.resumeAccepts();
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  public void start() {
    final Xnio xnio;
    try {
      // Do what org.jboss.as.remoting.XnioUtil does
      xnio =
          Xnio.getInstance(
              null,
              Module.getModuleFromCallerModuleLoader(
                      ModuleIdentifier.fromString("org.jboss.xnio.nio"))
                  .getClassLoader());
    } catch (Exception e) {
      throw new IllegalStateException(e.getLocalizedMessage());
    }
    try {
      // TODO make this configurable
      worker =
          xnio.createWorker(
              OptionMap.builder()
                  .set(Options.WORKER_IO_THREADS, 2)
                  .set(Options.WORKER_TASK_CORE_THREADS, 5)
                  .set(Options.WORKER_TASK_MAX_THREADS, 10)
                  .set(Options.TCP_NODELAY, true)
                  .set(Options.CORK, true)
                  .getMap());

      Builder serverOptionsBuilder =
          OptionMap.builder().set(Options.TCP_NODELAY, true).set(Options.REUSE_ADDRESSES, true);
      ChannelListener acceptListener = ChannelListeners.openListenerAdapter(openListener);
      if (httpAddress != null) {
        normalServer =
            worker.createStreamConnectionServer(
                httpAddress, acceptListener, serverOptionsBuilder.getMap());
        normalServer.resumeAccepts();
      }
      if (secureAddress != null) {
        if (sslClientAuthMode != null) {
          serverOptionsBuilder.set(SSL_CLIENT_AUTH_MODE, sslClientAuthMode);
        }
        OptionMap secureOptions = serverOptionsBuilder.getMap();
        XnioSsl xnioSsl = new UndertowXnioSsl(worker.getXnio(), secureOptions, sslContext);
        secureServer =
            xnioSsl.createSslConnectionServer(worker, secureAddress, acceptListener, secureOptions);
        secureServer.resumeAccepts();
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
 @BeforeClass
 public static void setup() throws IOException {
   DefaultServer.setRootHandler(AutobahnWebSocketServer.getRootHandler());
   Xnio xnio = Xnio.getInstance(DefaultServer.class.getClassLoader());
   worker =
       xnio.createWorker(
           OptionMap.builder()
               .set(Options.WORKER_IO_THREADS, 2)
               .set(Options.CONNECTION_HIGH_WATER, 1000000)
               .set(Options.CONNECTION_LOW_WATER, 1000000)
               .set(Options.WORKER_TASK_CORE_THREADS, 30)
               .set(Options.WORKER_TASK_MAX_THREADS, 30)
               .set(Options.TCP_NODELAY, true)
               .set(Options.CORK, true)
               .getMap());
 }
예제 #4
0
  public void start() throws IOException {
    log.infof("Starting JMX Remoting Server %s", Version.getVersionString());

    // Initialise general Remoting - this step would be implemented elsewhere when
    // running within an application server.
    final Xnio xnio = Xnio.getInstance();
    endpoint = Remoting.createEndpoint("JMXRemoting", xnio, OptionMap.EMPTY);
    endpoint.addConnectionProvider(
        "remote", new RemoteConnectionProviderFactory(), OptionMap.EMPTY);

    final NetworkServerProvider nsp =
        endpoint.getConnectionProviderInterface("remote", NetworkServerProvider.class);
    final SocketAddress bindAddress = new InetSocketAddress(host, listenerPort);
    final OptionMap serverOptions = createOptionMap();

    server = nsp.createServer(bindAddress, serverOptions, authenticationProvider, null);

    Map<String, Object> configMap = new HashMap<String, Object>();
    if (excludedVersions != null) {
      configMap.put(EXCLUDED_VERSIONS, excludedVersions);
    }
    // Initialise the components that will provide JMX connectivity.
    if (mbeanServerLocator == null) {
      connectorServer =
          new RemotingConnectorServer(
              mbeanServer, endpoint, configMap, serverMessageEventHandlerFactory);
      connectorServer.start();
    } else {
      delegatingServer =
          new DelegatingRemotingConnectorServer(
              mbeanServerLocator, endpoint, configMap, serverMessageEventHandlerFactory);
      delegatingServer.start();
    }
  }
 public UndertowXhrTransport(OptionMap optionMap) throws IOException {
   Assert.notNull(optionMap, "OptionMap is required");
   this.optionMap = optionMap;
   this.httpClient = UndertowClient.getInstance();
   this.worker = Xnio.getInstance().createWorker(optionMap);
   this.undertowBufferSupport =
       (undertow13Present ? new Undertow13BufferSupport() : new UndertowXnioBufferSupport());
 }
예제 #6
0
  public static void main(String[] args) throws Exception {

    // First define the listener that actually is run on each connection.
    final ChannelListener<ConnectedStreamChannel> readListener =
        new ChannelListener<ConnectedStreamChannel>() {
          public void handleEvent(ConnectedStreamChannel channel) {
            final ByteBuffer buffer = ByteBuffer.allocate(512);
            int res;
            try {
              while ((res = channel.read(buffer)) > 0) {
                buffer.flip();
                Channels.writeBlocking(channel, buffer);
              }
              // make sure everything is flushed out
              Channels.flushBlocking(channel);
              if (res == -1) {
                channel.close();
              } else {
                channel.resumeReads();
              }
            } catch (IOException e) {
              e.printStackTrace();
              IoUtils.safeClose(channel);
            }
          }
        };

    // Create an accept listener.
    final ChannelListener<AcceptingChannel<ConnectedStreamChannel>> acceptListener =
        new ChannelListener<AcceptingChannel<ConnectedStreamChannel>>() {
          public void handleEvent(final AcceptingChannel<ConnectedStreamChannel> channel) {
            try {
              ConnectedStreamChannel accepted;
              // channel is ready to accept zero or more connections
              while ((accepted = channel.accept()) != null) {
                System.out.println("accepted " + accepted.getPeerAddress());
                // stream channel has been accepted at this stage.
                accepted.getReadSetter().set(readListener);
                // read listener is set; start it up
                accepted.resumeReads();
              }
            } catch (IOException ignored) {
            }
          }
        };

    final XnioWorker worker = Xnio.getInstance().createWorker(OptionMap.EMPTY);
    // Create the server.
    AcceptingChannel<? extends ConnectedStreamChannel> server =
        worker.createStreamServer(new InetSocketAddress(12345), acceptListener, OptionMap.EMPTY);
    // lets start accepting connections
    server.resumeAccepts();

    System.out.println("Listening on " + server.getLocalAddress());
  }
  private void startServer() throws Exception {
    final Xnio xnio = Xnio.getInstance();
    endpoint = Remoting.createEndpoint("RemoteNaming", xnio, OptionMap.EMPTY);
    endpoint.addConnectionProvider(
        "remote", new RemoteConnectionProviderFactory(), OptionMap.EMPTY);
    final NetworkServerProvider nsp =
        endpoint.getConnectionProviderInterface("remote", NetworkServerProvider.class);
    final SocketAddress bindAddress = new InetSocketAddress("localhost", 7999);
    final OptionMap serverOptions = TestUtils.createOptionMap();

    server =
        nsp.createServer(
            bindAddress, serverOptions, new TestUtils.DefaultAuthenticationHandler(), null);
    remoteNamingService = new RemoteNamingService(localContext, Executors.newFixedThreadPool(10));
    remoteNamingService.start(endpoint);

    serverStopped = false;
  }
예제 #8
0
  public void start() throws IOException {
    log.infof("Starting JMX Remoting Server %s", Version.getVersionString());

    // Initialise general Remoting - this step would be implemented elsewhere when
    // running within an application server.
    final Xnio xnio = Xnio.getInstance();
    endpoint = Remoting.createEndpoint("JMXRemoting", xnio, OptionMap.EMPTY);
    endpoint.addConnectionProvider(
        "remote", new RemoteConnectionProviderFactory(), OptionMap.EMPTY);

    final NetworkServerProvider nsp =
        endpoint.getConnectionProviderInterface("remote", NetworkServerProvider.class);
    final SocketAddress bindAddress = new InetSocketAddress("localhost", listenerPort);
    final OptionMap serverOptions = createOptionMap();

    server = nsp.createServer(bindAddress, serverOptions, authenticationProvider, null);

    // Initialise the components that will provide JMX connectivity.
    connectorServer = new RemotingConnectorServer(mbeanServer, endpoint);
    connectorServer.start();
  }
 private WebSocketContainer getDefaultContainer() {
   if (defaultContainerDisabled) {
     return null;
   }
   if (defaultContainer != null) {
     return defaultContainer;
   }
   synchronized (UndertowContainerProvider.class) {
     if (defaultContainer == null) {
       try {
         // this is not great, as we have no way to control the lifecycle
         // but there is not much we can do
         // todo: what options should we use here?
         XnioWorker worker =
             Xnio.getInstance().createWorker(OptionMap.create(Options.THREAD_DAEMON, true));
         Pool<ByteBuffer> buffers =
             new ByteBufferSlicePool(
                 directBuffers
                     ? BufferAllocator.DIRECT_BYTE_BUFFER_ALLOCATOR
                     : BufferAllocator.BYTE_BUFFER_ALLOCATOR,
                 1024,
                 10240);
         defaultContainer =
             new ServerWebSocketContainer(
                 defaultIntrospector,
                 UndertowContainerProvider.class.getClassLoader(),
                 worker,
                 buffers,
                 new CompositeThreadSetupAction(Collections.<ThreadSetupAction>emptyList()),
                 !invokeInIoThread);
       } catch (IOException e) {
         throw new RuntimeException(e);
       }
     }
     return defaultContainer;
   }
 }
예제 #10
0
  public synchronized void start() {
    xnio = Xnio.getInstance(Undertow.class.getClassLoader());
    channels = new ArrayList<>();
    try {
      worker =
          xnio.createWorker(
              OptionMap.builder()
                  .set(Options.WORKER_IO_THREADS, ioThreads)
                  .set(Options.CONNECTION_HIGH_WATER, 1000000)
                  .set(Options.CONNECTION_LOW_WATER, 1000000)
                  .set(Options.WORKER_TASK_CORE_THREADS, workerThreads)
                  .set(Options.WORKER_TASK_MAX_THREADS, workerThreads)
                  .set(Options.TCP_NODELAY, true)
                  .set(Options.CORK, true)
                  .addAll(workerOptions)
                  .getMap());

      OptionMap socketOptions =
          OptionMap.builder()
              .set(Options.WORKER_IO_THREADS, ioThreads)
              .set(Options.TCP_NODELAY, true)
              .set(Options.REUSE_ADDRESSES, true)
              .set(Options.BALANCING_TOKENS, 1)
              .set(Options.BALANCING_CONNECTIONS, 2)
              .set(Options.BACKLOG, 1000)
              .addAll(this.socketOptions)
              .getMap();

      Pool<ByteBuffer> buffers =
          new ByteBufferSlicePool(
              directBuffers
                  ? BufferAllocator.DIRECT_BYTE_BUFFER_ALLOCATOR
                  : BufferAllocator.BYTE_BUFFER_ALLOCATOR,
              bufferSize,
              bufferSize * buffersPerRegion);

      for (ListenerConfig listener : listeners) {
        final HttpHandler rootHandler =
            listener.rootHandler != null ? listener.rootHandler : this.rootHandler;
        if (listener.type == ListenerType.AJP) {
          AjpOpenListener openListener = new AjpOpenListener(buffers, serverOptions);
          openListener.setRootHandler(rootHandler);
          ChannelListener<AcceptingChannel<StreamConnection>> acceptListener =
              ChannelListeners.openListenerAdapter(openListener);
          AcceptingChannel<? extends StreamConnection> server =
              worker.createStreamConnectionServer(
                  new InetSocketAddress(Inet4Address.getByName(listener.host), listener.port),
                  acceptListener,
                  socketOptions);
          server.resumeAccepts();
          channels.add(server);
        } else {
          OptionMap undertowOptions =
              OptionMap.builder()
                  .set(UndertowOptions.BUFFER_PIPELINED_DATA, true)
                  .addAll(serverOptions)
                  .getMap();
          if (listener.type == ListenerType.HTTP) {
            HttpOpenListener openListener = new HttpOpenListener(buffers, undertowOptions);
            openListener.setRootHandler(rootHandler);
            ChannelListener<AcceptingChannel<StreamConnection>> acceptListener =
                ChannelListeners.openListenerAdapter(openListener);
            AcceptingChannel<? extends StreamConnection> server =
                worker.createStreamConnectionServer(
                    new InetSocketAddress(Inet4Address.getByName(listener.host), listener.port),
                    acceptListener,
                    socketOptions);
            server.resumeAccepts();
            channels.add(server);
          } else if (listener.type == ListenerType.HTTPS) {
            ChannelListener<StreamConnection> openListener;

            HttpOpenListener httpOpenListener = new HttpOpenListener(buffers, undertowOptions);
            httpOpenListener.setRootHandler(rootHandler);

            boolean spdy = serverOptions.get(UndertowOptions.ENABLE_SPDY, false);
            boolean http2 = serverOptions.get(UndertowOptions.ENABLE_HTTP2, false);
            if (spdy || http2) {
              AlpnOpenListener alpn =
                  new AlpnOpenListener(buffers, undertowOptions, httpOpenListener);
              if (spdy) {
                SpdyOpenListener spdyListener =
                    new SpdyOpenListener(
                        buffers,
                        new ByteBufferSlicePool(BufferAllocator.BYTE_BUFFER_ALLOCATOR, 1024, 1024),
                        undertowOptions);
                spdyListener.setRootHandler(rootHandler);
                alpn.addProtocol(SpdyOpenListener.SPDY_3_1, spdyListener, 5);
              }
              if (http2) {
                Http2OpenListener http2Listener = new Http2OpenListener(buffers, undertowOptions);
                http2Listener.setRootHandler(rootHandler);
                alpn.addProtocol(Http2OpenListener.HTTP2, http2Listener, 10);
                alpn.addProtocol(Http2OpenListener.HTTP2_14, http2Listener, 7);
              }
              openListener = alpn;
            } else {
              openListener = httpOpenListener;
            }
            ChannelListener<AcceptingChannel<StreamConnection>> acceptListener =
                ChannelListeners.openListenerAdapter(openListener);
            XnioSsl xnioSsl;
            if (listener.sslContext != null) {
              xnioSsl =
                  new UndertowXnioSsl(
                      xnio,
                      OptionMap.create(Options.USE_DIRECT_BUFFERS, true),
                      listener.sslContext);
            } else {
              xnioSsl =
                  xnio.getSslProvider(
                      listener.keyManagers,
                      listener.trustManagers,
                      OptionMap.create(Options.USE_DIRECT_BUFFERS, true));
            }
            AcceptingChannel<SslConnection> sslServer =
                xnioSsl.createSslConnectionServer(
                    worker,
                    new InetSocketAddress(Inet4Address.getByName(listener.host), listener.port),
                    (ChannelListener) acceptListener,
                    socketOptions);
            sslServer.resumeAccepts();
            channels.add(sslServer);
          }
        }
      }

    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
예제 #11
0
  public void testAcceptor() throws Exception {
    threadFactory.clear();
    log.info("Test: testAcceptor");
    final CountDownLatch ioLatch = new CountDownLatch(4);
    final CountDownLatch closeLatch = new CountDownLatch(2);
    final AtomicBoolean clientOpened = new AtomicBoolean();
    final AtomicBoolean clientReadOnceOK = new AtomicBoolean();
    final AtomicBoolean clientReadDoneOK = new AtomicBoolean();
    final AtomicBoolean clientReadTooMuch = new AtomicBoolean();
    final AtomicBoolean clientWriteOK = new AtomicBoolean();
    final AtomicBoolean serverOpened = new AtomicBoolean();
    final AtomicBoolean serverReadOnceOK = new AtomicBoolean();
    final AtomicBoolean serverReadDoneOK = new AtomicBoolean();
    final AtomicBoolean serverReadTooMuch = new AtomicBoolean();
    final AtomicBoolean serverWriteOK = new AtomicBoolean();
    final byte[] bytes = "Ummagumma!".getBytes("UTF-8");
    final Xnio xnio = Xnio.getInstance("nio");
    final ReadChannelThread readChannelThread = xnio.createReadChannelThread(threadFactory);
    final ReadChannelThread clientReadChannelThread = xnio.createReadChannelThread(threadFactory);
    final WriteChannelThread writeChannelThread = xnio.createWriteChannelThread(threadFactory);
    final WriteChannelThread clientWriteChannelThread =
        xnio.createWriteChannelThread(threadFactory);
    final ConnectionChannelThread connectionChannelThread =
        xnio.createConnectionChannelThread(threadFactory);
    try {
      final FutureResult<InetSocketAddress> futureAddressResult =
          new FutureResult<InetSocketAddress>();
      final IoFuture<InetSocketAddress> futureAddress = futureAddressResult.getIoFuture();
      final IoFuture<? extends ConnectedStreamChannel> futureConnection =
          xnio.acceptStream(
              new InetSocketAddress(Inet4Address.getByAddress(new byte[] {127, 0, 0, 1}), 0),
              connectionChannelThread,
              clientReadChannelThread,
              clientWriteChannelThread,
              new ChannelListener<ConnectedStreamChannel>() {
                private final ByteBuffer inboundBuf = ByteBuffer.allocate(512);
                private int readCnt = 0;
                private final ByteBuffer outboundBuf = ByteBuffer.wrap(bytes);

                public void handleEvent(final ConnectedStreamChannel channel) {
                  channel
                      .getCloseSetter()
                      .set(
                          new ChannelListener<ConnectedStreamChannel>() {
                            public void handleEvent(final ConnectedStreamChannel channel) {
                              closeLatch.countDown();
                            }
                          });
                  channel
                      .getReadSetter()
                      .set(
                          new ChannelListener<ConnectedStreamChannel>() {
                            public void handleEvent(final ConnectedStreamChannel channel) {
                              try {
                                final int res = channel.read(inboundBuf);
                                if (res == 0) {
                                  channel.resumeReads();
                                } else if (res == -1) {
                                  serverReadDoneOK.set(true);
                                  ioLatch.countDown();
                                  channel.shutdownReads();
                                } else {
                                  final int ttl = readCnt += res;
                                  if (ttl == bytes.length) {
                                    serverReadOnceOK.set(true);
                                  } else if (ttl > bytes.length) {
                                    serverReadTooMuch.set(true);
                                    IoUtils.safeClose(channel);
                                    return;
                                  }
                                  channel.resumeReads();
                                }
                              } catch (IOException e) {
                                log.errorf(e, "Server read failed");
                                IoUtils.safeClose(channel);
                              }
                            }
                          });
                  channel
                      .getWriteSetter()
                      .set(
                          new ChannelListener<ConnectedStreamChannel>() {
                            public void handleEvent(final ConnectedStreamChannel channel) {
                              try {
                                channel.write(outboundBuf);
                                if (!outboundBuf.hasRemaining()) {
                                  serverWriteOK.set(true);
                                  Channels.shutdownWritesBlocking(channel);
                                  ioLatch.countDown();
                                }
                              } catch (IOException e) {
                                log.errorf(e, "Server write failed");
                                IoUtils.safeClose(channel);
                              }
                            }
                          });
                  channel.resumeReads();
                  channel.resumeWrites();
                  serverOpened.set(true);
                }
              },
              new ChannelListener<BoundChannel>() {
                public void handleEvent(final BoundChannel channel) {
                  futureAddressResult.setResult(channel.getLocalAddress(InetSocketAddress.class));
                }
              },
              OptionMap.create(Options.REUSE_ADDRESSES, Boolean.TRUE));
      final InetSocketAddress localAddress = futureAddress.get();
      final IoFuture<? extends ConnectedStreamChannel> ioFuture =
          xnio.connectStream(
              localAddress,
              connectionChannelThread,
              readChannelThread,
              writeChannelThread,
              new ChannelListener<ConnectedStreamChannel>() {
                private final ByteBuffer inboundBuf = ByteBuffer.allocate(512);
                private int readCnt = 0;
                private final ByteBuffer outboundBuf = ByteBuffer.wrap(bytes);

                public void handleEvent(final ConnectedStreamChannel channel) {
                  channel
                      .getCloseSetter()
                      .set(
                          new ChannelListener<ConnectedStreamChannel>() {
                            public void handleEvent(final ConnectedStreamChannel channel) {
                              closeLatch.countDown();
                            }
                          });
                  channel
                      .getReadSetter()
                      .set(
                          new ChannelListener<ConnectedStreamChannel>() {
                            public void handleEvent(final ConnectedStreamChannel channel) {
                              try {
                                final int res = channel.read(inboundBuf);
                                if (res == 0) {
                                  channel.resumeReads();
                                } else if (res == -1) {
                                  channel.shutdownReads();
                                  clientReadDoneOK.set(true);
                                  ioLatch.countDown();
                                } else {
                                  final int ttl = readCnt += res;
                                  if (ttl == bytes.length) {
                                    clientReadOnceOK.set(true);
                                  } else if (ttl > bytes.length) {
                                    clientReadTooMuch.set(true);
                                    IoUtils.safeClose(channel);
                                    return;
                                  }
                                  channel.resumeReads();
                                }
                              } catch (IOException e) {
                                log.errorf(e, "Client read failed");
                                IoUtils.safeClose(channel);
                              }
                            }
                          });
                  channel
                      .getWriteSetter()
                      .set(
                          new ChannelListener<ConnectedStreamChannel>() {
                            public void handleEvent(final ConnectedStreamChannel channel) {
                              try {
                                channel.write(outboundBuf);
                                if (!outboundBuf.hasRemaining()) {
                                  clientWriteOK.set(true);
                                  Channels.shutdownWritesBlocking(channel);
                                  ioLatch.countDown();
                                }
                              } catch (IOException e) {
                                log.errorf(e, "Client write failed");
                                IoUtils.safeClose(channel);
                              }
                            }
                          });
                  channel.resumeReads();
                  channel.resumeWrites();
                  clientOpened.set(true);
                }
              },
              null,
              OptionMap.EMPTY);
      assertTrue("Read timed out", ioLatch.await(500L, TimeUnit.MILLISECONDS));
      assertTrue("Close timed out", closeLatch.await(500L, TimeUnit.MILLISECONDS));
      assertFalse("Client read too much", clientReadTooMuch.get());
      assertTrue("Client read OK", clientReadOnceOK.get());
      assertTrue("Client read done", clientReadDoneOK.get());
      assertTrue("Client write OK", clientWriteOK.get());
      assertFalse("Server read too much", serverReadTooMuch.get());
      assertTrue("Server read OK", serverReadOnceOK.get());
      assertTrue("Server read done", serverReadDoneOK.get());
      assertTrue("Server write OK", serverWriteOK.get());
    } finally {
      readChannelThread.shutdown();
      writeChannelThread.shutdown();
      clientReadChannelThread.shutdown();
      clientWriteChannelThread.shutdown();
      connectionChannelThread.shutdown();
    }
    threadFactory.await();
  }
예제 #12
0
 private void doConnectionTest(
     final Runnable body,
     final ChannelListener<? super ConnectedStreamChannel> clientHandler,
     final ChannelListener<? super ConnectedStreamChannel> serverHandler)
     throws Exception {
   Xnio xnio = Xnio.getInstance("nio", NioTcpTestCase.class.getClassLoader());
   final ConnectionChannelThread connectionChannelThread =
       xnio.createConnectionChannelThread(threadFactory);
   final ConnectionChannelThread serverChannelThread =
       xnio.createConnectionChannelThread(threadFactory);
   final ReadChannelThread readChannelThread = xnio.createReadChannelThread(threadFactory);
   final ReadChannelThread clientReadChannelThread = xnio.createReadChannelThread(threadFactory);
   final WriteChannelThread writeChannelThread = xnio.createWriteChannelThread(threadFactory);
   final WriteChannelThread clientWriteChannelThread =
       xnio.createWriteChannelThread(threadFactory);
   try {
     final AcceptingChannel<? extends ConnectedStreamChannel> server =
         xnio.createStreamServer(
             new InetSocketAddress(
                 Inet4Address.getByAddress(new byte[] {127, 0, 0, 1}), SERVER_PORT),
             serverChannelThread,
             ChannelListeners.<ConnectedStreamChannel>openListenerAdapter(
                 readChannelThread,
                 writeChannelThread,
                 new CatchingChannelListener<ConnectedStreamChannel>(
                     serverHandler, threadFactory)),
             OptionMap.create(Options.REUSE_ADDRESSES, Boolean.TRUE));
     server.resumeAccepts();
     try {
       final IoFuture<? extends ConnectedStreamChannel> ioFuture =
           xnio.connectStream(
               new InetSocketAddress(
                   Inet4Address.getByAddress(new byte[] {127, 0, 0, 1}), SERVER_PORT),
               connectionChannelThread,
               clientReadChannelThread,
               clientWriteChannelThread,
               new CatchingChannelListener<ConnectedStreamChannel>(clientHandler, threadFactory),
               null,
               OptionMap.EMPTY);
       final ConnectedStreamChannel channel = ioFuture.get();
       try {
         body.run();
         channel.close();
         server.close();
       } catch (Exception e) {
         log.errorf(e, "Error running body");
         throw e;
       } catch (Error e) {
         log.errorf(e, "Error running body");
         throw e;
       } finally {
         IoUtils.safeClose(channel);
       }
     } finally {
       IoUtils.safeClose(server);
     }
   } finally {
     connectionChannelThread.shutdown();
     serverChannelThread.shutdown();
     clientReadChannelThread.shutdown();
     clientWriteChannelThread.shutdown();
     readChannelThread.shutdown();
     writeChannelThread.shutdown();
   }
   connectionChannelThread.awaitTermination();
   serverChannelThread.awaitTermination();
   readChannelThread.awaitTermination();
   writeChannelThread.awaitTermination();
   clientReadChannelThread.awaitTermination();
   clientWriteChannelThread.awaitTermination();
 }