CountDownLatch latch = new CountDownLatch(1); Vertx vertx = vertx(new VertxOptions().setMetricsOptions(new MetricsOptions().setEnabled(true).setFactory(factory))); Context ctx = contextFactory.apply(vertx); ctx.runOnContext(v1 -> { HttpServer server = vertx.createHttpServer().websocketHandler(ws -> { ws.handler(buf -> { ws.write(Buffer.buffer("bye")); }); }); server.listen(8080, "localhost", onSuccess(s -> { expectedThread.set(Thread.currentThread()); expectedContext.set(Vertx.currentContext()); latch.countDown(); })); }); awaitLatch(latch); HttpClient client = vertx.createHttpClient(); client.websocket(8080, "localhost", "/", ws -> { ws.handler(buf -> { ws.closeHandler(v -> { vertx.close(v4 -> { assertTrue(websocketConnected.get()); }); }); ws.close(); }); ws.write(Buffer.buffer("hello")); });
@Test public void testReportProtocolViolationOnClient() { server = vertx.createHttpServer(new HttpServerOptions().setPort(DEFAULT_HTTP_PORT)).requestHandler(req -> { NetSocket sock = getUpgradedNetSocket(req, "/some/path"); // Let's write an invalid frame Buffer buff = Buffer.buffer(); buff.appendByte((byte)(0x8)).appendByte((byte)0); // Violates protocol with V13 (final control frame) sock.write(buff); }); server.listen(ar -> { assertTrue(ar.succeeded()); client.websocketStream(DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, "/some/path", null, WebsocketVersion.V13). handler(ws -> { AtomicReference<Throwable> failure = new AtomicReference<>(); ws.closeHandler(v -> { assertNotNull(failure.get()); testComplete(); }); ws.exceptionHandler(failure::set); }); }); await(); }
@Test public void testCloseStatusCodeFromServer() throws InterruptedException { CountDownLatch latch = new CountDownLatch(2); client = vertx.createHttpClient(); server = vertx.createHttpServer(new HttpServerOptions().setPort(DEFAULT_HTTP_PORT)) .websocketHandler(socket -> { socket.closeHandler(a -> { latch.countDown(); }); vertx.setTimer(1000, (ar) -> socket.close()); }) .listen(ar -> { client.websocket(DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, "/", ws -> { ws.frameHandler(frame -> { assertEquals(1000, frame.binaryData().getByteBuf().getShort(0)); assertEquals(1000, frame.closeStatusCode()); assertNull(frame.closeReason()); latch.countDown(); }); }); }); awaitLatch(latch); }
@Override public void start() throws Exception { HttpClient client = vertx.createHttpClient(); client.websocket(8080, "localhost", "/some-uri", websocket -> { websocket.handler(data -> { System.out.println("Received data " + data.toString("ISO-8859-1")); client.close(); }); websocket.writeBinaryMessage(Buffer.buffer("Hello world")); }); } }
@Test public void testClearClientHandlersOnEnd() { String path = "/some/path"; server = vertx.createHttpServer(new HttpServerOptions().setPort(DEFAULT_HTTP_PORT)).websocketHandler(WebSocketBase::close); server.listen(ar -> { assertTrue(ar.succeeded()); client.websocketStream(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(); }
private SocketMessages testWriteTextMessages(List<String> messagesToSend, WebsocketVersion version) { String path = "/some/path"; server = vertx.createHttpServer(new HttpServerOptions().setPort(DEFAULT_HTTP_PORT)).websocketHandler(ws -> { for (String messageToSend : messagesToSend) { ws.writeTextMessage(messageToSend); } ws.close(); }); List<String> receivedMessages = new ArrayList<>(); List<Throwable> receivedExceptions = new ArrayList<>(); server.listen(ar -> { assertTrue(ar.succeeded()); client.websocket(DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, path, null, version, ws -> { ws.textMessageHandler(receivedMessages::add); ws.exceptionHandler(receivedExceptions::add); ws.closeHandler(v -> testComplete()); }); }); await(); return new SocketMessages(receivedMessages, receivedExceptions); }
@Test public void testCloseStatusCodeFromClient() throws InterruptedException { CountDownLatch latch = new CountDownLatch(2); client = vertx.createHttpClient(); server = vertx.createHttpServer(new HttpServerOptions().setPort(DEFAULT_HTTP_PORT)) .websocketHandler(socket -> { socket.closeHandler(a -> { latch.countDown(); }); socket.frameHandler(frame -> { assertEquals(1000, frame.binaryData().getByteBuf().getShort(0)); assertEquals(1000, frame.closeStatusCode()); assertNull(frame.closeReason()); latch.countDown(); }); }) .listen(ar -> { client.websocket(DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, "/", ws -> { ws.close(); }); }); awaitLatch(latch); }
/** * This does not set up a handler on the websocket */ private WebSocket setupRawWebsocketClient(String serverPath) throws InterruptedException { String requestURI = serverPath + "/websocket"; AtomicReference<WebSocket> openedWebSocketReference = new AtomicReference<>(); CountDownLatch openSocketCountDown = new CountDownLatch(1); client.websocket(requestURI, ws -> { openedWebSocketReference.set(ws); openSocketCountDown.countDown(); ws.endHandler(v -> testComplete()); ws.exceptionHandler(this::fail); }); openSocketCountDown.await(5, TimeUnit.SECONDS); return openedWebSocketReference.get(); }
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(DEFAULT_HTTP_PORT)); servers.add(theServer); theServer.websocketHandler(ws -> { connectedServers.add(theServer); Integer cnt = connectCount.get(theServer); icnt++; connectCount.put(theServer, icnt); latchConns.countDown(); }).listen(ar -> { if (ar.succeeded()) { latchListen.countDown(); CountDownLatch latchClient = new CountDownLatch(numConnections); for (int i = 0; i < numConnections; i++) { client.websocket(DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, "/someuri", ws -> { ws.closeHandler(v -> latchClient.countDown()); ws.close(); }); server.close(ar -> { assertTrue(ar.succeeded()); closeLatch.countDown();
/** * This sets up a handler on the websocket */ private WebSocket setupSockJsClient(String serverPath, List<Buffer> receivedMessagesCollector) throws InterruptedException { String requestURI = serverPath + "/000/000/websocket"; AtomicReference<WebSocket> openedWebSocketReference = new AtomicReference<>(); CountDownLatch openSocketCountDown = new CountDownLatch(1); client.websocket(requestURI, ws -> { openedWebSocketReference.set(ws); ws.handler(replyBuffer -> { log.debug("Client received " + replyBuffer); String textReply = replyBuffer.toString(); if ("o".equals(textReply)) { openSocketCountDown.countDown(); } else { receivedMessagesCollector.add(replyBuffer); } }); ws.endHandler(v -> testComplete()); ws.exceptionHandler(this::fail); }); openSocketCountDown.await(5, TimeUnit.SECONDS); return openedWebSocketReference.get(); }
createSignRequest(null, configCenter + url, headers, null)))); client.websocket(refreshPort, ipPort.getHostOrIp(), url, .addAll(authHeaders), ws -> { ws.exceptionHandler(e -> { LOGGER.error("watch config read fail", e); stopHeartBeatThread(); isWatching = false; }); ws.closeHandler(v -> { LOGGER.warn("watching config connection is closed accidentally"); stopHeartBeatThread(); }); ws.pongHandler(pong -> { ws.frameHandler(frame -> { Buffer action = frame.binaryData(); LOGGER.info("watching config recieved {}", action); Map<String, Object> mAction = action.toJsonObject().getMap(); if ("CREATE".equals(mAction.get("action"))) {
private void testReceiveFail(String address, Object body) throws Exception { CountDownLatch latch = new CountDownLatch(1); client.websocket(websocketURI, ws -> { // Register JsonObject msg = new JsonObject().put("type", "register").put("address", address); ws.writeFrame(io.vertx.core.http.WebSocketFrame.textFrame(msg.encode(), true)); ws.handler(buff -> fail("Shouldn't receive anything")); // Wait a bit to allow the handler to be setup on the server, then send message from eventbus vertx.setTimer(200, tid -> { vertx.eventBus().send(address, body); vertx.setTimer(200, tid2 -> latch.countDown()); }); }); awaitLatch(latch); }
private void testError(String msg, String expectedErr) throws Exception { CountDownLatch latch = new CountDownLatch(1); client.websocket(websocketURI, ws -> { ws.writeFrame(io.vertx.core.http.WebSocketFrame.textFrame(msg, true)); ws.handler(buff -> { String str = buff.toString(); JsonObject received = new JsonObject(str); assertEquals("err", received.getString("type")); assertEquals(expectedErr, received.getString("body")); latch.countDown(); }); }); awaitLatch(latch); }
@Test public void testConnectionClosedAfterPingTimeout() throws Exception { sockJSHandler.bridge(allAccessOptions.setPingTimeout(1000)); CountDownLatch latch = new CountDownLatch(1); long start = System.currentTimeMillis(); client.websocket(websocketURI, ws -> ws.closeHandler(v -> latch.countDown())); awaitLatch(latch); long dur = System.currentTimeMillis() - start; assertTrue(dur > 1000 && dur < 3000); }
public static CompletableFuture<Void> latchForEvent(MeshRestClient client, String event) throws Exception { // Construct latch in order to wait until the migration completed event was received CompletableFuture<Void> latch = new CompletableFuture<>(); CountDownLatch registerLatch = new CountDownLatch(1); client.eventbus(ws -> { // Register to events JsonObject msg = new JsonObject().put("type", "register").put("address", event); ws.writeFinalTextFrame(msg.encode()); // Handle the event ws.handler(buff -> { latch.complete(null); }); registerLatch.countDown(); }); failingLatch(registerLatch); return latch; }
private void testWriteFromConnectHandler(WebsocketVersion version) throws Exception { String path = "/some/path"; Buffer buff = Buffer.buffer("AAA"); server = vertx.createHttpServer(new HttpServerOptions().setPort(DEFAULT_HTTP_PORT)).websocketHandler(ws -> { assertEquals(path, ws.path()); ws.writeFrame(WebSocketFrame.binaryFrame(buff, true)); }); server.listen(ar -> { assertTrue(ar.succeeded()); client.websocket(DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, path, null, version, ws -> { Buffer received = Buffer.buffer(); ws.handler(data -> { received.appendBuffer(data); if (received.length() == buff.length()) { assertEquals(buff, received); ws.close(); testComplete(); } }); }); }); await(); }
vertx.runOnContext(v -> { runner.run(); }); server.listen(ar -> { assertTrue(ar.succeeded()); client.websocketStream(DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, path, null). handler(ws -> { Buffer buff = Buffer.buffer(); ws.handler(b -> { buff.appendBuffer(b); }); ws.endHandler(v -> { assertEquals("helloworld", buff.toString("UTF-8")); testComplete(); }); ws.write(Buffer.buffer("foo")); }); });
String continuationFrame = "BBB"; server = vertx.createHttpServer(new HttpServerOptions().setPort(DEFAULT_HTTP_PORT)).requestHandler(req -> { NetSocket sock = getUpgradedNetSocket(req, path); Buffer buff = Buffer.buffer(); buff.appendByte((byte) 0x01); // Incomplete Text frame buff.appendByte((byte) firstFrame.length()); buff.appendString(firstFrame); sock.write(buff); }); server.listen(ar -> { assertTrue(ar.succeeded()); client.websocket(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()) { } else if (receivedFirstFrame.get() && received.isFinal()) { assertEquals(continuationFrame, receivedBuffer.toString()); ws.close(); testComplete();
@Test public void testUnmaskedFrameRequest(){ client = vertx.createHttpClient(new HttpClientOptions().setSendUnmaskedFrames(true)); server = vertx.createHttpServer(new HttpServerOptions().setPort(DEFAULT_HTTP_PORT).setAcceptUnmaskedFrames(true)); server.requestHandler(req -> { req.response().setChunked(true).write("connect"); }); server.websocketHandler(ws -> { ws.handler(new Handler<Buffer>() { public void handle(Buffer data) { assertEquals(data.toString(), "first unmasked frame"); testComplete(); } }); }); server.listen(onSuccess(server -> { client.websocket(DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, "/", ws -> { ws.writeFinalTextFrame("first unmasked frame"); }); })); await(); }
@Test public void testServerWebSocket() { server = vertx.createHttpServer(); server.websocketHandler(ws -> { FakeHttpServerMetrics metrics = FakeMetricsBase.getMetrics(server); WebSocketMetric metric = metrics.getMetric(ws); assertNotNull(metric); assertNotNull(metric.soMetric); ws.handler(ws::write); ws.closeHandler(closed -> { assertNull(metrics.getMetric(ws)); testComplete(); }); }); server.listen(HttpTestBase.DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, ar -> { assertTrue(ar.succeeded()); client = vertx.createHttpClient(); client.websocket(HttpTestBase.DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, "/", ws -> { ws.write(Buffer.buffer("wibble")); ws.handler(buff -> ws.close()); }); }); await(); }