io.vertx.core.http.WebSocketFrame Java Examples

The following examples show how to use io.vertx.core.http.WebSocketFrame. 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: SockJSHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testTextFrameSockJs() throws InterruptedException {
  String serverPath = "/text-sockjs";
  setupSockJsServer(serverPath, this::echoRequest);

  List<Buffer> receivedMessages = new ArrayList<>();
  WebSocket openedWebSocket = setupSockJsClient(serverPath, receivedMessages);
  String messageToSend = "[\"testMessage\"]";
  openedWebSocket.writeFrame(WebSocketFrame.textFrame(messageToSend, true));

  await(5, TimeUnit.SECONDS);

  assertEquals("Client should have received 2 messages: the reply and the close.", 2, receivedMessages.size());
  Buffer expectedReply = Buffer.buffer("a" + messageToSend);
  assertEquals("Client reply should have matched request", expectedReply, receivedMessages.get(0));
  assertEquals("Final message should have been a close", SOCKJS_CLOSE_REPLY, receivedMessages.get(1));
}
 
Example #2
Source File: SockJSHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testTextFrameRawWebSocket() throws InterruptedException {
  String serverPath = "/textecho";
  setupSockJsServer(serverPath, this::echoRequest);

  String message = "hello";
  AtomicReference<String> receivedReply = new AtomicReference<>();
  WebSocket ws = setupRawWebsocketClient(serverPath);

  ws.handler(replyBuffer -> receivedReply.set(replyBuffer.toString()));

  ws.writeFrame(WebSocketFrame.textFrame(message, true));

  await(5, TimeUnit.SECONDS);

  assertEquals("Client reply should have matched request", message, receivedReply.get());
}
 
Example #3
Source File: WSConsumesTest.java    From vert.x-microservice with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleString() throws InterruptedException {
    final String message = "xhello";

    getClient().websocket(8080, "localhost", SERVICE_REST_GET + "/testSimpleString", ws -> {
        long startTime = System.currentTimeMillis();
        ws.handler((data) -> {
            System.out.println("client testSimpleString:" + new String(data.getBytes()));
            assertNotNull(data.getString(0, data.length()));
            assertTrue(data.getString(0, data.length()).equals(message));
            ws.close();
            long endTime = System.currentTimeMillis();
            System.out.println("Total execution time testSimpleString: " + (endTime - startTime) + "ms");
            testComplete();
        });

        ws.writeFrame(WebSocketFrame.textFrame(message, true));
    });


    await();

}
 
Example #4
Source File: SockJSHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendWebsocketContinuationFrames() {
  // Use raw websocket transport
  client.webSocket("/echo/websocket", onSuccess(ws -> {

    int size = 65535;

    Buffer buffer1 = TestUtils.randomBuffer(size);
    Buffer buffer2 = TestUtils.randomBuffer(size);

    ws.writeFrame(io.vertx.core.http.WebSocketFrame.binaryFrame(buffer1, false));
    ws.writeFrame(io.vertx.core.http.WebSocketFrame.continuationFrame(buffer2, true));

    Buffer received = Buffer.buffer();

    ws.handler(buff -> {
      received.appendBuffer(buff);
      if (received.length() == size * 2) {
        testComplete();
      }
    });

  }));

  await();
}
 
Example #5
Source File: WebSocketRouter.java    From festival with Apache License 2.0 5 votes vote down vote up
public void doActive(ServerWebSocket serverWebSocket, WebSocketFrame frame) {
    if (active == null) {
        return;
    }
    try {
        ReflectUtils.invokeMethod(bean, active, serverWebSocket, frame);
    } catch (InvocationTargetException e) {
        throw new IllegalStateException(e.getCause());
    }
}
 
Example #6
Source File: SockJSHandlerTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testSplitLargeReplySockJs() throws InterruptedException {
  String serverPath = "/large-reply-sockjs";

  String largeMessage = TestUtils.randomAlphaString(65536 * 2);
  Buffer largeReplyBuffer = Buffer.buffer(largeMessage);

  setupSockJsServer(serverPath, (sock, requestBuffer) -> {
    sock.write(largeReplyBuffer);
    sock.close();
  });

  List<Buffer> receivedMessages = new ArrayList<>();
  WebSocket openedWebSocket = setupSockJsClient(serverPath, receivedMessages);

  String messageToSend = "[\"hello\"]";
  openedWebSocket.writeFrame(WebSocketFrame.textFrame(messageToSend, true));

  await(5, TimeUnit.SECONDS);

  int receivedReplyCount = receivedMessages.size();
  assertTrue("Should have received > 2 reply frame, actually received " + receivedReplyCount, receivedReplyCount > 2);

  Buffer expectedReplyBuffer = Buffer.buffer("a[\"").appendBuffer(largeReplyBuffer).appendBuffer(Buffer.buffer("\"]"));
  Buffer clientReplyBuffer = combineReplies(receivedMessages.subList(0, receivedMessages.size() - 1));
  assertEquals(String.format("Combined reply on client (length %s) should equal message from server (%s)",
    clientReplyBuffer.length(), expectedReplyBuffer.length()),
    expectedReplyBuffer, clientReplyBuffer);

  Buffer finalMessage = receivedMessages.get(receivedMessages.size() - 1);
  assertEquals("Final message should have been a close", SOCKJS_CLOSE_REPLY, finalMessage);
}
 
Example #7
Source File: SockJSHandlerTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testCombineTextFrameSockJs() throws InterruptedException {
  String serverPath = "/text-combine-sockjs";
  setupSockJsServer(serverPath, this::echoRequest);

  List<Buffer> receivedMessages = new ArrayList<>();
  WebSocket openedWebSocket = setupSockJsClient(serverPath, receivedMessages);

  Buffer largeMessage = Buffer.buffer("[\"" + TestUtils.randomAlphaString(30) + "\"]");
  WebSocketFrame frame1 = new WebSocketFrameImpl(FrameType.TEXT, largeMessage.slice(0, 10).getByteBuf(), false);
  WebSocketFrame frame2 = WebSocketFrame.continuationFrame(largeMessage.slice(10, 20), false);
  WebSocketFrame frame3 = WebSocketFrame.continuationFrame(largeMessage.slice(20, largeMessage.length()), true);

  log.debug("Client sending " + frame1.textData());
  openedWebSocket.writeFrame(frame1);
  log.debug("Client sending " + frame2.textData());
  openedWebSocket.writeFrame(frame2);
  log.debug("Client sending " + frame3.textData());
  openedWebSocket.writeFrame(frame3);

  await(5, TimeUnit.SECONDS);

  assertEquals("Client should have received 2 messages: the reply and the close.", 2, receivedMessages.size());
  Buffer expectedReply = Buffer.buffer("a" + largeMessage.toString());
  assertEquals("Client reply should have matched request", expectedReply, receivedMessages.get(0));
  assertEquals("Final message should have been a close", SOCKJS_CLOSE_REPLY, receivedMessages.get(1));
}
 
Example #8
Source File: SockJSHandlerTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testSplitLargeReplyRawWebSocket() throws InterruptedException {
  String serverPath = "/split";

  String largeReply = TestUtils.randomAlphaString(65536 * 5);
  Buffer largeReplyBuffer = Buffer.buffer(largeReply);

  setupSockJsServer(serverPath, (sock, requestBuffer) -> {
    sock.write(largeReplyBuffer);
    sock.close();
  });

  Buffer totalReplyBuffer = Buffer.buffer(largeReplyBuffer.length());
  AtomicInteger receivedReplies = new AtomicInteger(0);
  WebSocket ws = setupRawWebsocketClient(serverPath);
  ws.handler(replyBuffer -> {
    totalReplyBuffer.appendBuffer(replyBuffer);
    receivedReplies.incrementAndGet();

  });

  ws.writeFrame(WebSocketFrame.binaryFrame(Buffer.buffer("hello"), true));

  await(5, TimeUnit.SECONDS);

  int receivedReplyCount = receivedReplies.get();
  assertEquals("Combined reply on client should equal message from server", largeReplyBuffer, totalReplyBuffer);
  assertTrue("Should have received > 1 reply frame, actually received " + receivedReplyCount, receivedReplyCount > 1);
}
 
Example #9
Source File: SockJSHandlerTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
/**
 * Writing multiple continuation frames from the client side should result in a single message on the server side
 * after the frames are re-combined
 */
@Test
public void testCombineBinaryContinuationFramesRawWebSocket() throws InterruptedException {
  String serverPath = "/combine";

  AtomicReference<Buffer> serverReceivedMessage = new AtomicReference<>();
  setupSockJsServer(serverPath, (sock, requestBuffer) -> {
    serverReceivedMessage.set(requestBuffer);
    sock.write(Buffer.buffer("reply"));
    sock.close();
  });


  Buffer largeMessage = Buffer.buffer(TestUtils.randomAlphaString(30));
  WebSocketFrame frame1 = WebSocketFrame.binaryFrame(largeMessage.slice(0, 10), false);
  WebSocketFrame frame2 = WebSocketFrame.continuationFrame(largeMessage.slice(10, 20), false);
  WebSocketFrame frame3 = WebSocketFrame.continuationFrame(largeMessage.slice(20, largeMessage.length()), true);

  WebSocket ws = setupRawWebsocketClient(serverPath);
  ws.writeFrame(frame1);
  ws.writeFrame(frame2);
  ws.writeFrame(frame3);

  await(5, TimeUnit.SECONDS);

  assertEquals("Server did not combine continuation frames correctly", largeMessage, serverReceivedMessage.get());
}
 
Example #10
Source File: ApolloWSHandlerTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryWsCallMultipleFrames() {
  testQueryWsCall((webSocket, message) -> {
    Buffer buffer = message.toBuffer();
    int part = buffer.length() / 3;
    if (part == 0) fail("Cannot perform test");
    webSocket.writeFrame(WebSocketFrame.binaryFrame(buffer.getBuffer(0, part), false));
    webSocket.writeFrame(WebSocketFrame.continuationFrame(buffer.getBuffer(part, 2 * part), false));
    webSocket.writeFrame(WebSocketFrame.continuationFrame(buffer.getBuffer(2 * part, buffer.length()), true));
  });
}
 
Example #11
Source File: WebSocketTestController.java    From festival with Apache License 2.0 5 votes vote down vote up
@OnActive
public void active(ServerWebSocket serverWebSocket, WebSocketFrame webSocketFrame) {
    log.info("active......");
    JsonObject jsonObject = new JsonObject();
    jsonObject.put("type", 1);
    jsonObject.put("data", "hello");
    serverWebSocket.writeTextMessage(jsonObject.encodePrettily());
}
 
Example #12
Source File: WebSocketServiceTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void webSocketDoesNotToHandlePingPayloadAsJsonRpcRequest(final TestContext context) {
  final Async async = context.async();

  httpClient.webSocket(
      "/",
      result -> {
        WebSocket websocket = result.result();

        websocket.handler(
            buffer -> {
              final String payload = buffer.toString();
              if (!payload.equals("foo")) {
                context.fail("Only expected PONG response with same payload as PING request");
              }
            });

        websocket.closeHandler(
            h -> {
              verifyNoInteractions(webSocketRequestHandlerSpy);
              async.complete();
            });

        websocket.writeFrame(WebSocketFrame.pingFrame(Buffer.buffer("foo")));
        websocket.close();
      });

  async.awaitSuccess(VERTX_AWAIT_TIMEOUT_MILLIS);
}
 
Example #13
Source File: ServerWebSocketWrapper.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Override
public ServerWebSocket writeFrame(WebSocketFrame frame, Handler<AsyncResult<Void>> handler) {
  delegate.writeFrame(frame, handler);
  return this;
}
 
Example #14
Source File: ServerWebSocketWrapper.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Override
public ServerWebSocket frameHandler(Handler<WebSocketFrame> handler) {
  delegate.frameHandler(handler);
  return this;
}
 
Example #15
Source File: ServerWebSocketWrapper.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Override
public Future<Void> writeFrame(WebSocketFrame frame) {
  return delegate.writeFrame(frame);
}
 
Example #16
Source File: WebSocketBridgeTest.java    From vertx-stomp with Apache License 2.0 4 votes vote down vote up
@Test
/*
    Constructs a message with size == 2*MAX_WEBSOCKET_FRAME_SIZE. The message is then sent via
    eventBus bridge. The test then reads the message via WebSocket and makes sure that the message
    is delivered in three WebSocketFrames.
    Regression for #35
 */
public void testSendingAMessageBiggerThanSocketFrameSize() {
  AtomicReference<Throwable> error = new AtomicReference<>();
  List<WebSocketFrame> wsBuffers = new ArrayList<>();
  List<Buffer> stompBuffers = new ArrayList<>();

  AtomicReference<WebSocket> socket = new AtomicReference<>();
  AtomicReference<StompClientConnection> client = new AtomicReference<>();

  clients.add(StompClient.create(vertx).connect(61613, "localhost", connection -> {
    connection.result().subscribe("bigData", h-> {}, r -> {
      client.set(connection.result());

    });
    connection.result().receivedFrameHandler(stompFrame -> {
      if(stompFrame.toBuffer().toString().startsWith("MESSAGE")) {
        stompBuffers.add(stompFrame.toBuffer());
      }
    });
  }));

  vertx.createHttpClient().webSocket(options, ar -> {
    if (ar.succeeded()) {
      WebSocket ws = ar.result();
      AtomicBoolean inMsg = new AtomicBoolean();
      ws.exceptionHandler(error::set)
        .frameHandler(frame -> {
          if (!frame.isContinuation()) {
            if (frame.isBinary()) {
              String data = frame.binaryData().toString();
              if (data.startsWith("CONNECTED")) {
                ws.write(
                  new Frame(Frame.Command.SUBSCRIBE, Headers.create("id", "myId", "destination", "bigData"), null)
                    .toBuffer());
              }
              if (data.startsWith("MESSAGE")) {
                // Start collecting the frames once we see the first real payload message
                inMsg.set(true);
                wsBuffers.add(frame);
              } else {
                inMsg.set(false);
              }
            }
          } else if (inMsg.get()) {
            wsBuffers.add(frame);
          }
        })
        .write(new Frame(Frame.Command.CONNECT, Headers.create("accept-version", "1.2,1.1,1.0",
          "heart-beat", "10000,10000"), null).toBuffer());
      socket.set(ws);
    }
  });

  // Create content that is slightly bigger than the size of a single web socket frame
  String bufferContent = StringUtils.repeat("*",  2 * MAX_WEBSOCKET_FRAME_SIZE);

  await().atMost(10, TimeUnit.SECONDS).until(() -> client.get() != null);
  await().atMost(10, TimeUnit.SECONDS).until(() -> socket.get() != null);
  vertx.eventBus().publish("bigData",bufferContent);

  await().atMost(10, TimeUnit.SECONDS).until(() -> error.get() == null && stompBuffers.size() == 1);
  await().atMost(10, TimeUnit.SECONDS).until(() -> error.get() == null && wsBuffers.size() == 3);

  // STOMP message has 2048 bytes of payload + headers => 2167 bytes
  assertEquals(2167, stompBuffers.get(0).getBytes().length);

  // We expect two complete frames + 1 with 116 bytes
  assertEquals(MAX_WEBSOCKET_FRAME_SIZE, wsBuffers.get(0).binaryData().getBytes().length);
  assertEquals(MAX_WEBSOCKET_FRAME_SIZE, wsBuffers.get(1).binaryData().getBytes().length);
  assertEquals(116, wsBuffers.get(2).binaryData().getBytes().length);
  socket.get().close();
}
 
Example #17
Source File: VoiceWebsocket.java    From kyoko with MIT License 4 votes vote down vote up
private void onDisconnected(WebSocketFrame frame) {
    isOpen = false;
    logger.debug("The audio connection was closed!");
    logger.debug("by client? {}, reason: {}, code: {}", closedByClient, frame.closeReason(), frame.closeStatusCode());
    close(ConnectionStatus.NOT_CONNECTED);
}
 
Example #18
Source File: WebSocketTestController.java    From festival with Apache License 2.0 4 votes vote down vote up
@OnActive
public void active(ServerWebSocket serverWebSocket, WebSocketFrame webSocketFrame) {
    log.info("active......");
    serverWebSocket.writeTextMessage("hi");
}