Example #1
0
 @Test
 public void testMultipleServerClose() {
   this.server =
       vertx.createHttpServer(new HttpServerOptions().setPort(HttpTestBase.DEFAULT_HTTP_PORT));
   AtomicInteger times = new AtomicInteger();
   // We assume the endHandler and the close completion handler are invoked in the same context
   // task
   ThreadLocal stack = new ThreadLocal();
   stack.set(true);
   server
       .websocketStream()
       .endHandler(
           v -> {
             assertNull(stack.get());
             assertTrue(Vertx.currentContext().isEventLoopContext());
             times.incrementAndGet();
           });
   server.close(
       ar1 -> {
         assertNull(stack.get());
         assertTrue(Vertx.currentContext().isEventLoopContext());
         server.close(
             ar2 -> {
               server.close(
                   ar3 -> {
                     assertEquals(1, times.get());
                     testComplete();
                   });
             });
       });
   await();
 }
Example #2
0
 @Test
 public void testSharedServersRoundRobinButFirstStartAndStopServer() throws Exception {
   // Start and stop a server on the same port/host before hand to make sure it doesn't interact
   CountDownLatch latch = new CountDownLatch(1);
   HttpServer theServer = vertx.createHttpServer(new HttpServerOptions().setPort(4321));
   theServer
       .websocketHandler(
           ws -> {
             fail("Should not connect");
           })
       .listen(
           ar -> {
             if (ar.succeeded()) {
               latch.countDown();
             } else {
               fail("Failed to bind server");
             }
           });
   awaitLatch(latch);
   CountDownLatch closeLatch = new CountDownLatch(1);
   theServer.close(
       ar -> {
         assertTrue(ar.succeeded());
         closeLatch.countDown();
       });
   assertTrue(closeLatch.await(10, TimeUnit.SECONDS));
   testSharedServersRoundRobin();
 }
Example #3
0
  /**
   * Handles starting the server listening on all interfaces
   *
   * @return a callback to hit when ready for the server to open up listening
   */
  private Handler<Message<Object>> getStartupHandler() {
    return message -> {
      server = vertx.createHttpServer();
      Router router = Router.router(vertx);

      GraphApi graphApi = new GraphApi(session, vertx, registry);

      if (isInitializerThread()) {
        graphApi.outputApi(logger);
      }
      graphApi.init(router);

      server.requestHandler(router::accept);

      server.listen(
          svrConfig.port,
          "0.0.0.0",
          event -> {
            if (event.failed()) {
              logger.error("Failed to start server, error:", event.cause());
              stop();
            } else {
              logger.info("Thread: {} starting to handle request", Thread.currentThread().getId());
            }
          });
    };
  }
Example #4
0
 @Test
 public void testWebsocketStreamCallbackAsynchronously() {
   this.server =
       vertx.createHttpServer(new HttpServerOptions().setPort(HttpTestBase.DEFAULT_HTTP_PORT));
   AtomicInteger done = new AtomicInteger();
   ServerWebSocketStream stream = server.websocketStream();
   stream.handler(req -> {});
   ThreadLocal<Object> stack = new ThreadLocal<>();
   stack.set(true);
   stream.endHandler(
       v -> {
         assertTrue(Vertx.currentContext().isEventLoopContext());
         assertNull(stack.get());
         if (done.incrementAndGet() == 2) {
           testComplete();
         }
       });
   server.listen(
       ar -> {
         assertTrue(Vertx.currentContext().isEventLoopContext());
         assertNull(stack.get());
         ThreadLocal<Object> stack2 = new ThreadLocal<>();
         stack2.set(true);
         server.close(
             v -> {
               assertTrue(Vertx.currentContext().isEventLoopContext());
               assertNull(stack2.get());
               if (done.incrementAndGet() == 2) {
                 testComplete();
               }
             });
         stack2.set(null);
       });
   await();
 }
  @Override
  public void start() throws Exception {

    HttpServer server = vertx.createHttpServer();
    server.requestHandler(
        new Handler<HttpServerRequest>() {

          @Override
          public void handle(HttpServerRequest request) {
            request
                .response()
                .sendFile(
                    '.' + (request.path().equals("/") ? "/resource/index.html" : request.path()));
          }
        });

    server.websocketHandler(
        new Handler<ServerWebSocket>() {

          @Override
          public void handle(final ServerWebSocket ws) {
            if (!ws.path().equals("/chat")) {
              ws.reject();
              return;
            }
            final LocalMap<Object, String> wsSessions =
                vertx.sharedData().getLocalMap("websocket.chat.sessions");
            if (wsSessions == null) {
              System.out.println("Deu erro!");
            }
            wsSessions.put(ws.textHandlerID(), ws.textHandlerID());

            ws.handler(
                new Handler<Buffer>() {

                  @Override
                  public void handle(Buffer buffer) {
                    for (String handlerId : wsSessions.values()) {
                      System.err.println("Sending " + handlerId);
                      vertx.eventBus().send(handlerId, buffer.toString());
                    }
                  }
                });

            ws.closeHandler(
                new Handler<Void>() {

                  @Override
                  public void handle(Void v) {
                    System.err.println("Socket closed. Removing" + ws.binaryHandlerID());
                    wsSessions.remove(ws.textHandlerID());
                  }
                });
          }
        });

    server.listen(8080);
  }
Example #6
0
 @Test
 public void testWebsocketPauseAndResume() {
   client.close();
   client = vertx.createHttpClient(new HttpClientOptions().setConnectTimeout(1000));
   String path = "/some/path";
   this.server =
       vertx.createHttpServer(
           new HttpServerOptions().setAcceptBacklog(1).setPort(HttpTestBase.DEFAULT_HTTP_PORT));
   AtomicBoolean paused = new AtomicBoolean();
   ReadStream<ServerWebSocket> stream = server.websocketStream();
   stream.handler(
       ws -> {
         assertFalse(paused.get());
         ws.writeMessage(Buffer.buffer("whatever"));
         ws.close();
       });
   server.listen(
       listenAR -> {
         assertTrue(listenAR.succeeded());
         stream.pause();
         paused.set(true);
         client
             .websocket(HttpTestBase.DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, path)
             .exceptionHandler(
                 err -> {
                   assertTrue(paused.get());
                   assertTrue(err instanceof WebSocketHandshakeException);
                   paused.set(false);
                   stream.resume();
                   client.connectWebsocket(
                       HttpTestBase.DEFAULT_HTTP_PORT,
                       HttpTestBase.DEFAULT_HTTP_HOST,
                       path,
                       ws -> {
                         ws.handler(
                             buffer -> {
                               assertEquals("whatever", buffer.toString("UTF-8"));
                               ws.closeHandler(
                                   v2 -> {
                                     testComplete();
                                   });
                             });
                       });
                 })
             .handler(ws -> fail());
       });
   await();
 }
Example #7
0
  private void testReject(WebsocketVersion version) throws Exception {

    String path = "/some/path";

    server =
        vertx
            .createHttpServer(new HttpServerOptions().setPort(HttpTestBase.DEFAULT_HTTP_PORT))
            .websocketHandler(
                ws -> {
                  assertEquals(path, ws.path());
                  ws.reject();
                });

    server.listen(
        ar -> {
          assertTrue(ar.succeeded());
          client
              .websocket(
                  HttpTestBase.DEFAULT_HTTP_PORT,
                  HttpTestBase.DEFAULT_HTTP_HOST,
                  path,
                  null,
                  version)
              .exceptionHandler(t -> testComplete())
              .handler(ws -> fail("Should not be called"));
        });
    await();
  }
Example #8
0
 private void testWriteMessage(int size, WebsocketVersion version) {
   String path = "/some/path";
   byte[] expected = TestUtils.randomByteArray(size);
   server =
       vertx
           .createHttpServer(new HttpServerOptions().setPort(HttpTestBase.DEFAULT_HTTP_PORT))
           .websocketHandler(
               ws -> {
                 ws.writeMessage(Buffer.buffer(expected));
                 ws.close();
               });
   server.listen(
       ar -> {
         assertTrue(ar.succeeded());
         client.connectWebsocket(
             HttpTestBase.DEFAULT_HTTP_PORT,
             HttpTestBase.DEFAULT_HTTP_HOST,
             path,
             null,
             version,
             ws -> {
               Buffer actual = Buffer.buffer();
               ws.handler(actual::appendBuffer);
               ws.closeHandler(
                   v -> {
                     assertArrayEquals(expected, actual.getBytes());
                     testComplete();
                   });
             });
       });
   await();
 }
Example #9
0
 private void testInvalidSubProtocol(WebsocketVersion version) throws Exception {
   String path = "/some/path";
   String subProtocol = "myprotocol";
   server =
       vertx
           .createHttpServer(
               new HttpServerOptions()
                   .setPort(HttpTestBase.DEFAULT_HTTP_PORT)
                   .setWebsocketSubProtocol("invalid"))
           .websocketHandler(ws -> {});
   server.listen(
       onSuccess(
           ar -> {
             client
                 .websocket(
                     HttpTestBase.DEFAULT_HTTP_PORT,
                     HttpTestBase.DEFAULT_HTTP_HOST,
                     path,
                     null,
                     version,
                     subProtocol)
                 .exceptionHandler(
                     t -> {
                       // Should fail
                       testComplete();
                     })
                 .handler(ws -> {});
           }));
   await();
 }
Example #10
0
 @Override
 public void stop() {
   if (server != null) {
     server.close();
     System.out.println("Server shut down.");
   }
 }
Example #11
0
 @Test
 public void testClearClientHandlersOnEnd() {
   String path = "/some/path";
   server =
       vertx
           .createHttpServer(new HttpServerOptions().setPort(HttpTestBase.DEFAULT_HTTP_PORT))
           .websocketHandler(WebSocketBase::close);
   server.listen(
       ar -> {
         assertTrue(ar.succeeded());
         client
             .websocket(HttpTestBase.DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, path, null)
             .handler(
                 ws -> {
                   ws.endHandler(
                       v -> {
                         try {
                           ws.endHandler(null);
                           ws.exceptionHandler(null);
                           ws.handler(null);
                         } catch (Exception e) {
                           fail(
                               "Was expecting to set to null the handlers when the socket is closed");
                           return;
                         }
                         testComplete();
                       });
                 });
       });
   await();
 }
Example #12
0
 @Test
 public void testEndHandlerCalled() {
   String path = "/some/path";
   server =
       vertx
           .createHttpServer(new HttpServerOptions().setPort(HttpTestBase.DEFAULT_HTTP_PORT))
           .websocketHandler(WebSocketBase::close);
   AtomicInteger doneCount = new AtomicInteger();
   server.listen(
       ar -> {
         assertTrue(ar.succeeded());
         client
             .websocket(HttpTestBase.DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, path, null)
             .endHandler(done -> doneCount.incrementAndGet())
             .handler(
                 ws -> {
                   assertEquals(0, doneCount.get());
                   ws.closeHandler(
                       v -> {
                         assertEquals(1, doneCount.get());
                         testComplete();
                       });
                 });
       });
   await();
 }
Example #13
0
 private void createServer() {
   server = vertx.createHttpServer();
   Router router = Router.router(vertx);
   router.route().handler(BodyHandler.create());
   configureBasicRouter(router);
   server.requestHandler(router::accept).listen(PORT);
   System.out.println("Server " + this.getClass().getTypeName() + " is started.");
 }
  @Override
  public void start() throws Exception {

    HttpServer server = vertx.createHttpServer();

    router = Router.router(vertx);

    // So we can use getBodyAsJson() and/or getBodyAsString() in our handling methods
    router.route().handler(BodyHandler.create());

    //		  router.post("/api/timeTest/namez").handler(this::PostChoir);

    RegisterRoutes();

    System.out.println("Now listening on port 3030");

    server.requestHandler(router::accept).listen(3030);
  }
Example #15
0
  @Override
  public void start() throws Exception {
    // Creating web server and its router
    HttpServerOptions httpServerOptions =
        new HttpServerOptions()
            .setCompressionSupported(true) // enabling gzip and deflate compression
            .setPort(80); // web port
    HttpServer server = vertx.createHttpServer(httpServerOptions);
    Router router = Router.router(vertx);

    // Logging web requests
    router.route("/*").handler(LoggerHandler.create());

    // Serving static files under the webroot folder
    router.route("/*").handler(StaticHandler.create());

    // Binding the web port
    server.requestHandler(router::accept).listen();
  }
Example #16
0
  // ---- run vertx server ---
  @Override
  public void start() throws Exception {
    // TODO Auto-generated method stub
    Set<String> scanPackages = new LinkedHashSet<String>();
    scanPackages.add("org.vsg");

    Router router = Router.router(vertx);

    /*
    Injector injector = Guice.createInjector(
    		new JsrRestControllerModule(router , runtimeClassLoader , scanPackages));
    		*/

    // JsrRestControllerModule  modInst =  injector.getInstance(JsrRestControllerModule.class);

    HttpServer httpServer = vertx.createHttpServer();

    httpServer.requestHandler(router::accept).listen(8090);
    logger.info("Startuped server on port : [8090]");
  }
  @Override
  public void start() throws Exception {
    address = MQTTSession.ADDRESS;

    JsonObject conf = config();

    localBridgePort = conf.getInteger("local_bridge_port", 7007);
    idleTimeout = conf.getInteger("socket_idle_timeout", 120);
    ssl_cert_key = conf.getString("ssl_cert_key");
    ssl_cert = conf.getString("ssl_cert");
    ssl_trust = conf.getString("ssl_trust");

    // [WebSocket -> BUS] listen WebSocket publish to BUS
    HttpServerOptions opt =
        new HttpServerOptions()
            .setTcpKeepAlive(true)
            .setIdleTimeout(idleTimeout)
            .setPort(localBridgePort);

    if (ssl_cert_key != null && ssl_cert != null && ssl_trust != null) {
      opt.setSsl(true)
          .setClientAuth(ClientAuth.REQUIRED)
          .setPemKeyCertOptions(
              new PemKeyCertOptions().setKeyPath(ssl_cert_key).setCertPath(ssl_cert))
          .setPemTrustOptions(new PemTrustOptions().addCertPath(ssl_trust));
    }

    netServer = vertx.createHttpServer(opt);
    netServer
        .websocketHandler(
            sock -> {
              final EventBusWebsocketBridge ebnb =
                  new EventBusWebsocketBridge(sock, vertx.eventBus(), address);
              sock.closeHandler(
                  aVoid -> {
                    logger.info(
                        "Bridge Server - closed connection from client ip: "
                            + sock.remoteAddress());
                    ebnb.stop();
                  });
              sock.exceptionHandler(
                  throwable -> {
                    logger.error("Bridge Server - Exception: " + throwable.getMessage(), throwable);
                    ebnb.stop();
                  });

              logger.info("Bridge Server - new connection from client ip: " + sock.remoteAddress());

              RecordParser parser = ebnb.initialHandhakeProtocolParser();
              sock.handler(parser::handle);
            })
        .listen();
  }
Example #18
0
  private void testContinuationWriteFromConnectHandler(WebsocketVersion version) throws Exception {
    String path = "/some/path";
    String firstFrame = "AAA";
    String continuationFrame = "BBB";

    server =
        vertx
            .createHttpServer(new HttpServerOptions().setPort(HttpTestBase.DEFAULT_HTTP_PORT))
            .requestHandler(
                req -> {
                  NetSocket sock = getUpgradedNetSocket(req, path);

                  // Let's write a Text frame raw
                  Buffer buff = Buffer.buffer();
                  buff.appendByte((byte) 0x01); // Incomplete Text frame
                  buff.appendByte((byte) firstFrame.length());
                  buff.appendString(firstFrame);
                  sock.write(buff);

                  buff = Buffer.buffer();
                  buff.appendByte((byte) (0x00 | 0x80)); // Complete continuation frame
                  buff.appendByte((byte) continuationFrame.length());
                  buff.appendString(continuationFrame);
                  sock.write(buff);
                });

    server.listen(
        ar -> {
          assertTrue(ar.succeeded());
          client.connectWebsocket(
              HttpTestBase.DEFAULT_HTTP_PORT,
              HttpTestBase.DEFAULT_HTTP_HOST,
              path,
              null,
              version,
              ws -> {
                AtomicBoolean receivedFirstFrame = new AtomicBoolean();
                ws.frameHandler(
                    received -> {
                      Buffer receivedBuffer = Buffer.buffer(received.textData());
                      if (!received.isFinal()) {
                        assertEquals(firstFrame, receivedBuffer.toString());
                        receivedFirstFrame.set(true);
                      } else if (receivedFirstFrame.get() && received.isFinal()) {
                        assertEquals(continuationFrame, receivedBuffer.toString());
                        ws.close();
                        testComplete();
                      }
                    });
              });
        });
    await();
  }
Example #19
0
 @Test
 public void testSharedServersRoundRobinWithOtherServerRunningOnDifferentPort() throws Exception {
   // Have a server running on a different port to make sure it doesn't interact
   CountDownLatch latch = new CountDownLatch(1);
   HttpServer theServer = vertx.createHttpServer(new HttpServerOptions().setPort(4321));
   theServer
       .websocketHandler(
           ws -> {
             fail("Should not connect");
           })
       .listen(
           ar -> {
             if (ar.succeeded()) {
               latch.countDown();
             } else {
               fail("Failed to bind server");
             }
           });
   awaitLatch(latch);
   testSharedServersRoundRobin();
 }
Example #20
0
 @Test
 public void testClosingServerClosesWebSocketStreamEndHandler() {
   this.server =
       vertx.createHttpServer(new HttpServerOptions().setPort(HttpTestBase.DEFAULT_HTTP_PORT));
   ReadStream<ServerWebSocket> stream = server.websocketStream();
   AtomicBoolean closed = new AtomicBoolean();
   stream.endHandler(v -> closed.set(true));
   stream.handler(ws -> {});
   server.listen(
       ar -> {
         assertTrue(ar.succeeded());
         assertFalse(closed.get());
         server.close(
             v -> {
               assertTrue(ar.succeeded());
               assertTrue(closed.get());
               testComplete();
             });
       });
   await();
 }
Example #21
0
  public static void main(String[] args) {
    Vertx vertx = null;
    HttpServer server = Vertx.vertx().createHttpServer();

    Router router = Router.router(vertx);
    Route route = router.route().path("/some/path/");

    route.handler(
        routingContext -> {
          // This handler will be called for the following request paths:

          // `/some/path`
          // `/some/path/`
          // `/some/path//`
          //
          // but not:
          // `/some/path/subdir`

          // This handler will be called for every request
          HttpServerResponse response = routingContext.response();
          response.putHeader("content-type", "text/plain");

          // Write to the response and end it
          response.end("Hello World from Vert.x-Web! Some path, Simple REST");
        });
    router
        .route()
        .handler(
            routingContext -> {

              // This handler will be called for every request
              HttpServerResponse response = routingContext.response();
              response.putHeader("content-type", "text/plain");

              // Write to the response and end it
              response.end("Hello World from Vert.x-Web!");
            });

    server.requestHandler(router::accept).listen(8080);
  }
Example #22
0
 protected void tearDown() throws Exception {
   client.close();
   if (server != null) {
     CountDownLatch latch = new CountDownLatch(1);
     server.close(
         ar -> {
           assertTrue(ar.succeeded());
           latch.countDown();
         });
     awaitLatch(latch);
   }
   super.tearDown();
 }
Example #23
0
  private void testWSWriteStream(WebsocketVersion version) throws Exception {

    String path = "/some/path";
    String query = "foo=bar&wibble=eek";
    String uri = path + "?" + query;

    server =
        vertx
            .createHttpServer(new HttpServerOptions().setPort(HttpTestBase.DEFAULT_HTTP_PORT))
            .websocketHandler(
                ws -> {
                  assertEquals(uri, ws.uri());
                  assertEquals(path, ws.path());
                  assertEquals(query, ws.query());
                  assertEquals("Upgrade", ws.headers().get("Connection"));
                  ws.handler(data -> ws.write(data));
                });

    server.listen(
        ar -> {
          assertTrue(ar.succeeded());
          int bsize = 100;
          int sends = 10;

          client.connectWebsocket(
              HttpTestBase.DEFAULT_HTTP_PORT,
              HttpTestBase.DEFAULT_HTTP_HOST,
              path + "?" + query,
              null,
              version,
              ws -> {
                final Buffer received = Buffer.buffer();
                ws.handler(
                    data -> {
                      received.appendBuffer(data);
                      if (received.length() == bsize * sends) {
                        ws.close();
                        testComplete();
                      }
                    });
                final Buffer sent = Buffer.buffer();
                for (int i = 0; i < sends; i++) {
                  Buffer buff = Buffer.buffer(TestUtils.randomByteArray(bsize));
                  ws.write(buff);
                  sent.appendBuffer(buff);
                }
              });
        });
    await();
  }
Example #24
0
  private Twinkle() {
    final Logger logger = LoggerFactory.getLogger(Twinkle.class);

    final Vertx vertx = Vertx.vertx(vertxOptions());
    final HttpServer httpServer = vertx.createHttpServer(httpServerOptions());
    final Router router = Router.router(vertx);

    router.get("/ping").handler(context -> context.response().end("pong"));
    router.mountSubRouter("/stats", new Metrics(vertx, httpServer).router());

    httpServer
        .requestHandler(router::accept)
        .listen(
            8080,
            result -> {
              if (result.succeeded()) {
                logger.info("Twinkle started");
              } else {
                logger.error("Twinkle failed to start", result.cause());
                vertx.close(shutdown -> logger.info("Twinkle shut down"));
              }
            });
  }
Example #25
0
 @Override
 public void stop() {
   logger.info("Stopping the server");
   try {
     if (server != null) {
       server.close();
     }
   } finally {
     // Only one thread can close the vertx as vertx is shared across all instances.
     Long shutdownThreadId = sharedData.putIfAbsent("shutdown", Thread.currentThread().getId());
     if (shutdownThreadId == null) {
       vertx.close(
           event -> {
             logger.info("Vertx instance closed");
             System.exit(-1);
           });
     }
   }
 }
Example #26
0
 private void testValidSubProtocol(WebsocketVersion version) throws Exception {
   String path = "/some/path";
   String subProtocol = "myprotocol";
   Buffer buff = Buffer.buffer("AAA");
   server =
       vertx
           .createHttpServer(
               new HttpServerOptions()
                   .setPort(HttpTestBase.DEFAULT_HTTP_PORT)
                   .setWebsocketSubProtocol(subProtocol))
           .websocketHandler(
               ws -> {
                 assertEquals(path, ws.path());
                 ws.writeFrame(WebSocketFrame.binaryFrame(buff, true));
               });
   server.listen(
       ar -> {
         assertTrue(ar.succeeded());
         client.connectWebsocket(
             HttpTestBase.DEFAULT_HTTP_PORT,
             HttpTestBase.DEFAULT_HTTP_HOST,
             path,
             null,
             version,
             subProtocol,
             ws -> {
               final Buffer received = Buffer.buffer();
               ws.handler(
                   data -> {
                     received.appendBuffer(data);
                     if (received.length() == buff.length()) {
                       assertEquals(buff, received);
                       ws.close();
                       testComplete();
                     }
                   });
             });
       });
   await();
 }
Example #27
0
  @Test
  // Let's manually handle the websocket handshake and write a frame to the client
  public void testHandleWSManually() throws Exception {
    String path = "/some/path";
    String message = "here is some text data";

    server =
        vertx
            .createHttpServer(new HttpServerOptions().setPort(HttpTestBase.DEFAULT_HTTP_PORT))
            .requestHandler(
                req -> {
                  NetSocket sock = getUpgradedNetSocket(req, path);
                  // Let's write a Text frame raw
                  Buffer buff = Buffer.buffer();
                  buff.appendByte((byte) 129); // Text frame
                  buff.appendByte((byte) message.length());
                  buff.appendString(message);
                  sock.write(buff);
                });
    server.listen(
        ar -> {
          assertTrue(ar.succeeded());
          client
              .websocket(HttpTestBase.DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, path)
              .exceptionHandler(t -> fail(t.getMessage()))
              .handler(
                  ws -> {
                    ws.handler(
                        buff -> {
                          assertEquals(message, buff.toString("UTF-8"));
                          testComplete();
                        });
                  });
        });
    await();
  }
 @Override
 public void stop() throws Exception {
   netServer.close();
 }
Example #29
0
  @Test
  public void testSharedServersRoundRobin() throws Exception {

    int numServers = 5;
    int numConnections = numServers * 100;

    List<HttpServer> servers = new ArrayList<>();
    Set<HttpServer> connectedServers = new ConcurrentHashSet<>();
    Map<HttpServer, Integer> connectCount = new ConcurrentHashMap<>();

    CountDownLatch latchListen = new CountDownLatch(numServers);
    CountDownLatch latchConns = new CountDownLatch(numConnections);
    for (int i = 0; i < numServers; i++) {
      HttpServer theServer =
          vertx.createHttpServer(new HttpServerOptions().setPort(HttpTestBase.DEFAULT_HTTP_PORT));
      servers.add(theServer);
      theServer
          .websocketHandler(
              ws -> {
                connectedServers.add(theServer);
                Integer cnt = connectCount.get(theServer);
                int icnt = cnt == null ? 0 : cnt;
                icnt++;
                connectCount.put(theServer, icnt);
                latchConns.countDown();
              })
          .listen(
              ar -> {
                if (ar.succeeded()) {
                  latchListen.countDown();
                } else {
                  fail("Failed to bind server");
                }
              });
    }
    assertTrue(latchListen.await(10, TimeUnit.SECONDS));

    // Create a bunch of connections
    CountDownLatch latchClient = new CountDownLatch(numConnections);
    for (int i = 0; i < numConnections; i++) {
      client.connectWebsocket(
          HttpTestBase.DEFAULT_HTTP_PORT,
          HttpTestBase.DEFAULT_HTTP_HOST,
          "/someuri",
          ws -> {
            ws.closeHandler(v -> latchClient.countDown());
            ws.close();
          });
    }

    assertTrue(latchClient.await(10, TimeUnit.SECONDS));
    assertTrue(latchConns.await(10, TimeUnit.SECONDS));

    assertEquals(numServers, connectedServers.size());
    for (HttpServer server : servers) {
      assertTrue(connectedServers.contains(server));
    }
    assertEquals(numServers, connectCount.size());
    for (int cnt : connectCount.values()) {
      assertEquals(numConnections / numServers, cnt);
    }

    CountDownLatch closeLatch = new CountDownLatch(numServers);

    for (HttpServer server : servers) {
      server.close(
          ar -> {
            assertTrue(ar.succeeded());
            closeLatch.countDown();
          });
    }

    assertTrue(closeLatch.await(10, TimeUnit.SECONDS));

    testComplete();
  }
Example #30
0
  private void testWSFrames(boolean binary, WebsocketVersion version) throws Exception {

    String path = "/some/path";
    String query = "foo=bar&wibble=eek";
    String uri = path + "?" + query;

    // version 0 doesn't support continuations so we just send 1 frame per message
    int frames = version == WebsocketVersion.V00 ? 1 : 10;

    server =
        vertx
            .createHttpServer(new HttpServerOptions().setPort(HttpTestBase.DEFAULT_HTTP_PORT))
            .websocketHandler(
                ws -> {
                  assertEquals(uri, ws.uri());
                  assertEquals(path, ws.path());
                  assertEquals(query, ws.query());
                  assertEquals("Upgrade", ws.headers().get("Connection"));
                  AtomicInteger count = new AtomicInteger();
                  ws.frameHandler(
                      frame -> {
                        if (count.get() == 0) {
                          if (binary) {
                            assertTrue(frame.isBinary());
                            assertFalse(frame.isText());
                          } else {
                            assertFalse(frame.isBinary());
                            assertTrue(frame.isText());
                          }
                          assertFalse(frame.isContinuation());
                        } else {
                          assertFalse(frame.isBinary());
                          assertFalse(frame.isText());
                          assertTrue(frame.isContinuation());
                        }
                        if (count.get() == frames - 1) {
                          assertTrue(frame.isFinal());
                        } else {
                          assertFalse(frame.isFinal());
                        }
                        ws.writeFrame(frame);
                        if (count.incrementAndGet() == frames) {
                          count.set(0);
                        }
                      });
                });

    server.listen(
        ar -> {
          assertTrue(ar.succeeded());
          int bsize = 100;

          int msgs = 10;

          client.connectWebsocket(
              HttpTestBase.DEFAULT_HTTP_PORT,
              HttpTestBase.DEFAULT_HTTP_HOST,
              path + "?" + query,
              null,
              version,
              ws -> {
                final List<Buffer> sent = new ArrayList<>();
                final List<Buffer> received = new ArrayList<>();

                AtomicReference<Buffer> currentReceived = new AtomicReference<>(Buffer.buffer());
                ws.frameHandler(
                    frame -> {
                      // received.appendBuffer(frame.binaryData());
                      currentReceived.get().appendBuffer(frame.binaryData());
                      if (frame.isFinal()) {
                        received.add(currentReceived.get());
                        currentReceived.set(Buffer.buffer());
                      }
                      if (received.size() == msgs) {
                        int pos = 0;
                        for (Buffer rec : received) {
                          assertEquals(rec, sent.get(pos++));
                        }
                        testComplete();
                      }
                    });

                AtomicReference<Buffer> currentSent = new AtomicReference<>(Buffer.buffer());
                for (int i = 0; i < msgs; i++) {
                  for (int j = 0; j < frames; j++) {
                    Buffer buff;
                    WebSocketFrame frame;
                    if (binary) {
                      buff = Buffer.buffer(TestUtils.randomByteArray(bsize));
                      if (j == 0) {
                        frame = WebSocketFrame.binaryFrame(buff, false);
                      } else {
                        frame = WebSocketFrame.continuationFrame(buff, j == frames - 1);
                      }
                    } else {
                      String str = TestUtils.randomAlphaString(bsize);
                      buff = Buffer.buffer(str);
                      if (j == 0) {
                        frame = WebSocketFrame.textFrame(str, false);
                      } else {
                        frame = WebSocketFrame.continuationFrame(buff, j == frames - 1);
                      }
                    }
                    currentSent.get().appendBuffer(buff);
                    ws.writeFrame(frame);
                    if (j == frames - 1) {
                      sent.add(currentSent.get());
                      currentSent.set(Buffer.buffer());
                    }
                  }
                }
              });
        });
    await();
  }