コード例 #1
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();
 }
コード例 #2
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();
  }
コード例 #3
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();
  }
コード例 #4
0
  @Test
  public void writeTwoDifferentMessages() throws Exception {
    byte[] bytes = {0x1, 0x3, 0x5, 0x7};
    String strContent = "foo";

    _wsStream.write(Buffer.buffer(bytes));
    _wsStream.finishCurrentMessage();

    _wsStream.setDataFormat(DataFormat.Text);
    _wsStream.write(Buffer.buffer(strContent.getBytes(StandardCharsets.UTF_8)));
    _wsStream.finishCurrentMessage();

    verify(_socket).writeFrame(binaryFrameEq(true, bytes));
    verify(_socket).writeFrame(textFrameEq(true, strContent));
  }
コード例 #5
0
ファイル: ClusteredMessage.java プロジェクト: CowLeo/vert.x
 public Buffer encodeToWire() {
   int length = 1024; // TODO make this configurable
   Buffer buffer = Buffer.buffer(length);
   buffer.appendInt(0);
   buffer.appendByte(WIRE_PROTOCOL_VERSION);
   byte systemCodecID = messageCodec.systemCodecID();
   buffer.appendByte(systemCodecID);
   if (systemCodecID == -1) {
     // User codec
     writeString(buffer, messageCodec.name());
   }
   buffer.appendByte(send ? (byte) 0 : (byte) 1);
   writeString(buffer, address);
   if (replyAddress != null) {
     writeString(buffer, replyAddress);
   } else {
     buffer.appendInt(0);
   }
   buffer.appendInt(sender.port);
   writeString(buffer, sender.host);
   encodeHeaders(buffer);
   writeBody(buffer);
   buffer.setInt(0, buffer.length() - 4);
   return buffer;
 }
コード例 #6
0
 @Override
 public void encodeToWire(Buffer buffer, String entries) {
   byte[] encoded = entries.getBytes(CharsetUtil.UTF_8);
   buffer.appendInt(encoded.length);
   Buffer buff = Buffer.buffer(encoded);
   buffer.appendBuffer(buff);
 }
コード例 #7
0
 private Buffer getAnalogValueCallbackThresholdDefault() {
   Buffer buffer = Buffer.buffer();
   buffer.appendBytes(Utils.getCharRandomValue(1));
   buffer.appendBytes(Utils.get2ByteURandomValue(1));
   buffer.appendBytes(Utils.get2ByteURandomValue(1));
   return buffer;
 }
コード例 #8
0
 @Override
 public void end(String chunk, String enc) {
   synchronized (getLock()) {
     Objects.requireNonNull(enc, "no null encoding accepted");
     end(Buffer.buffer(chunk, enc));
   }
 }
コード例 #9
0
  @Override
  public void render(
      RoutingContext context, String templateFileName, Handler<AsyncResult<Buffer>> handler) {
    try {
      Template template = cache.get(templateFileName);
      if (template == null) {
        // real compile
        synchronized (this) {
          loader.setVertx(context.vertx());
          // Compile
          template = config.getTemplate(adjustLocation(templateFileName));
        }
        cache.put(templateFileName, template);
      }

      Map<String, RoutingContext> variables = new HashMap<>(1);
      variables.put("context", context);

      try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        template.process(variables, new OutputStreamWriter(baos));
        handler.handle(Future.succeededFuture(Buffer.buffer(baos.toByteArray())));
      }

    } catch (Exception ex) {
      handler.handle(Future.failedFuture(ex));
    }
  }
コード例 #10
0
  @Test
  public void writeOneByteAndClose() throws Exception {
    byte b = 0x13; // arbitrary byte
    _wsStream.write(Buffer.buffer(new byte[] {b}));
    _wsStream.finishCurrentMessage(); // should flush and send websocket frame

    verify(_socket).writeFrame(binaryFrameEq(true, new byte[] {b}));
  }
コード例 #11
0
 @Override
 public HttpClientRequestImpl write(String chunk) {
   synchronized (getLock()) {
     checkComplete();
     checkResponseHandler();
     return write(Buffer.buffer(chunk));
   }
 }
コード例 #12
0
  @Test
  public void writeMultipleBytesAndClose() throws Exception {
    byte[] bytes = {0x1, 0x3, 0x5, 0x7};
    _wsStream.write(Buffer.buffer(bytes));
    _wsStream.finishCurrentMessage();

    verify(_socket).writeFrame(binaryFrameEq(true, bytes));
  }
コード例 #13
0
ファイル: JsonObject.java プロジェクト: PNRSoft/framework
 @Override
 public Buffer writeToBuffer() {
   String encoded = encode();
   byte[] bytes = encoded.getBytes();
   Buffer buffer = Buffer.buffer(bytes.length + 4);
   buffer.appendInt(bytes.length);
   buffer.appendBytes(bytes);
   return buffer;
 }
コード例 #14
0
 @Override
 public HttpClientRequestImpl write(String chunk, String enc) {
   synchronized (getLock()) {
     Objects.requireNonNull(enc, "no null encoding accepted");
     checkComplete();
     checkResponseHandler();
     return write(Buffer.buffer(chunk, enc));
   }
 }
コード例 #15
0
  private void writeToTarget(String sendPacket, String cmd) {
    logger.debug(name_log + "writeToDCU(), Command: " + cmd);

    // Writing Data to The Socket
    Buffer outBuffer = Buffer.buffer();
    outBuffer.setString(0, sendPacket);
    logger.info(name_log + "SEND[" + outBuffer.length() + "]> \n" + outBuffer.toString() + "\n");

    netSocket.write(outBuffer);
  }
コード例 #16
0
  @Test
  public void writeUnicodeFrameAndClose() throws Exception {
    String unicodeStr = "\u0628\u00de";

    _wsStream.setDataFormat(DataFormat.Text);
    _wsStream.write(Buffer.buffer(unicodeStr.getBytes(StandardCharsets.UTF_8)));
    _wsStream.finishCurrentMessage();

    verify(_socket).writeFrame(textFrameEq(true, unicodeStr));
  }
コード例 #17
0
  @Test
  public void streamAutoFlushesFrames() throws Exception {
    byte[] bytes = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};

    _wsStream.write(Buffer.buffer(bytes));

    verify(_socket).writeFrame(binaryFrameEq(false, Arrays.copyOfRange(bytes, 0, 5)));
    verify(_socket).writeFrame(continuationFrameEq(false, Arrays.copyOfRange(bytes, 5, 10)));

    _wsStream.finishCurrentMessage();
    verify(_socket).writeFrame(continuationFrameEq(true, Arrays.copyOfRange(bytes, 10, 11)));
  }
コード例 #18
0
ファイル: NetSocketImpl.java プロジェクト: karianna/vert.x
 @Override
 public synchronized NetSocket resume() {
   if (paused) {
     paused = false;
     if (pendingData != null) {
       // Send empty buffer to trigger sending of pending data
       context.runOnContext(v -> handleDataReceived(Buffer.buffer()));
     }
     doResume();
   }
   return this;
 }
コード例 #19
0
 @Override
 public void onToken(byte[] token, boolean timeout) throws Exception {
   try {
     Buffer buffer = Buffer.buffer(token);
     AbstractMessage message = decoder.dec(buffer);
     onMessageFromClient(message);
   } catch (Throwable ex) {
     String clientInfo = getClientInfo();
     Container.logger().error(clientInfo + ", Bad error in processing the message", ex);
     closeConnection();
   }
 }
コード例 #20
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();
 }
コード例 #21
0
  private Buffer getIdentity(Packet packet) {
    logger.debug("function getIdentity");
    if (packet.getResponseExpected()) {
      byte length = (byte) 8 + 25;
      byte functionId = FUNCTION_GET_IDENTITY;
      byte flags = (byte) 0;
      Buffer header = Utils.createHeader(uidBytes, length, functionId, packet.getOptions(), flags);
      Buffer buffer = Buffer.buffer();
      buffer.appendBuffer(header);
      buffer.appendBuffer(Utils.getIdentityPayload(uidString, uidBytes, DEVICE_IDENTIFIER));
      return buffer;
    }

    return null;
  }
コード例 #22
0
 private Buffer setVoltageCallbackThreshold(Packet packet) {
   logger.debug("function setVoltageCallbackThreshold");
   if (packet.getResponseExpected()) {
     byte length = (byte) 8 + 0;
     byte functionId = FUNCTION_SET_VOLTAGE_CALLBACK_THRESHOLD;
     byte flags = (byte) 0;
     Buffer header = Utils.createHeader(uidBytes, length, functionId, packet.getOptions(), flags);
     Buffer buffer = Buffer.buffer();
     buffer.appendBuffer(header);
     // TODO response expected bei settern
     return buffer;
   }
   this.voltageCallbackThreshold = packet.getPayload();
   return null;
 }
コード例 #23
0
 private Buffer setAnalogValueCallbackPeriod(Packet packet) {
   logger.debug("function setAnalogValueCallbackPeriod");
   if (packet.getResponseExpected()) {
     byte length = (byte) 8 + 0;
     byte functionId = FUNCTION_SET_ANALOG_VALUE_CALLBACK_PERIOD;
     byte flags = (byte) 0;
     Buffer header = Utils.createHeader(uidBytes, length, functionId, packet.getOptions(), flags);
     Buffer buffer = Buffer.buffer();
     buffer.appendBuffer(header);
     // TODO response expected bei settern
     return buffer;
   }
   this.analogValueCallbackPeriod = packet.getPayload();
   return null;
 }
コード例 #24
0
  private Buffer getAnalogValueCallbackThreshold(Packet packet) {
    logger.debug("function getAnalogValueCallbackThreshold");
    if (packet.getResponseExpected()) {
      byte length = (byte) 8 + 5;
      byte functionId = FUNCTION_GET_ANALOG_VALUE_CALLBACK_THRESHOLD;
      byte flags = (byte) 0;
      Buffer header = Utils.createHeader(uidBytes, length, functionId, packet.getOptions(), flags);
      Buffer buffer = Buffer.buffer();
      buffer.appendBuffer(header);
      buffer.appendBuffer(this.analogValueCallbackThreshold);
      return buffer;
    }

    return null;
  }
コード例 #25
0
  private Buffer getVoltageCallbackPeriod(Packet packet) {
    logger.debug("function getVoltageCallbackPeriod");
    if (packet.getResponseExpected()) {
      byte length = (byte) 8 + 4;
      byte functionId = FUNCTION_GET_VOLTAGE_CALLBACK_PERIOD;
      byte flags = (byte) 0;
      Buffer header = Utils.createHeader(uidBytes, length, functionId, packet.getOptions(), flags);
      Buffer buffer = Buffer.buffer();
      buffer.appendBuffer(header);
      buffer.appendBuffer(this.voltageCallbackPeriod);
      return buffer;
    }

    return null;
  }
コード例 #26
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();
 }
コード例 #27
0
  private Buffer getVoltage(Packet packet) {
    logger.debug("function getVoltage");
    if (packet.getResponseExpected()) {
      byte length = (byte) 8 + 2;
      byte functionId = FUNCTION_GET_VOLTAGE;
      byte flags = (byte) 0;
      Buffer header = Utils.createHeader(uidBytes, length, functionId, packet.getOptions(), flags);
      Buffer buffer = Buffer.buffer();
      buffer.appendBuffer(header);
      buffer.appendBytes(Utils.get2ByteURandomValue(1));

      return buffer;
    }

    return null;
  }
コード例 #28
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();
  }
コード例 #29
0
 private Buffer body() {
   if (body == null) {
     body = Buffer.buffer();
   }
   return body;
 }
コード例 #30
0
 private Buffer getVoltageCallbackPeriodDefault() {
   Buffer buffer = Buffer.buffer();
   buffer.appendBytes(Utils.get4ByteURandomValue(1));
   return buffer;
 }