io.vertx.core.buffer.Buffer类的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(11.2k)|赞(0)|评价(0)|浏览(485)

本文整理了Java中io.vertx.core.buffer.Buffer类的一些代码示例,展示了Buffer类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Buffer类的具体详情如下:
包路径:io.vertx.core.buffer.Buffer
类名称:Buffer

Buffer介绍

[英]Most data is shuffled around inside Vert.x using buffers.

A buffer is a sequence of zero or more bytes that can read from or written to and which expands automatically as necessary to accommodate any bytes written to it. You can perhaps think of a buffer as smart byte array.

Please consult the documentation for more information on buffers.
[中]大多数数据都在Vert内部混洗。x使用缓冲区。
缓冲区是一个由零个或多个字节组成的序列,可以读取或写入,并根据需要自动扩展以容纳写入它的任何字节。您也许可以将缓冲区视为智能字节数组。
有关缓冲区的更多信息,请参阅文档。

代码示例

代码示例来源:origin: eclipse-vertx/vert.x

private Buffer loadJsonAsBuffer(URL url) {
 try {
  Buffer encoded = new JsonObject(Json.mapper.readValue(url, Map.class)).toBuffer();
  return Buffer.buffer().appendInt(encoded.length()).appendBuffer(encoded);
 } catch (IOException e) {
  throw new RuntimeException(e);
 }
}

代码示例来源:origin: eclipse-vertx/vert.x

private void viaString(Buffer buffer) throws Exception {
 int pos = 0;
 int length = buffer.getInt(pos);
 pos += 4;
 byte[] encoded = buffer.getBytes(pos, pos + length);
 String str = new String(encoded, CharsetUtil.UTF_8);
 consume(new JsonObject(str));
}

代码示例来源:origin: vert-x3/vertx-examples

public Image(Vertx vertx, String name) {
 try {
  final BufferedImage raster = ImageIO.read(((VertxInternal) vertx).resolveFile(name));
  width = raster.getWidth();
  height = raster.getHeight();
  data = raster.getRGB(0, 0, width, height, null, 0, width);
  for (int pixel : data)
   if (!colorMap.containsKey(pixel)) {
    BufferedImage offlineImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = offlineImage.createGraphics();
    g2.setPaint(new Color(pixel, true));
    g2.fillRect(0, 0, 1, 1);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ImageIO.write(offlineImage, "PNG", out);
    colorMap.put(pixel, Buffer.buffer().appendBytes(out.toByteArray()));
    out.close();
    g2.dispose();
   }
 } catch (IOException e) {
  throw new RuntimeException(e);
 }
}

代码示例来源:origin: eclipse-vertx/vert.x

@Override
public void encodeToWire(Buffer buffer, Buffer b) {
 buffer.appendInt(b.length());
 buffer.appendBuffer(b);
}

代码示例来源:origin: eclipse-vertx/vert.x

@Override
public void encodeToWire(Buffer buffer, byte[] byteArray) {
 buffer.appendInt(byteArray.length);
 buffer.appendBytes(byteArray);
}

代码示例来源:origin: eclipse-vertx/vert.x

@Override
public void encodeToWire(Buffer buffer, JsonObject jsonObject) {
 Buffer encoded = jsonObject.toBuffer();
 buffer.appendInt(encoded.length());
 buffer.appendBuffer(encoded);
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testServerActualPortWhenSet() {
 server
   .requestHandler(request -> {
    request.response().end("hello");
   })
   .listen(ar -> {
    assertEquals(ar.result().actualPort(), DEFAULT_HTTP_PORT);
    vertx.createHttpClient(createBaseClientOptions()).getNow(ar.result().actualPort(), DEFAULT_HTTP_HOST, "/", onSuccess(response -> {
     assertEquals(response.statusCode(), 200);
     response.bodyHandler(body -> {
      assertEquals(body.toString("UTF-8"), "hello");
      testComplete();
     });
    }));
   });
 await();
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testSendFileFromClasspath() {
 vertx.createHttpServer(new HttpServerOptions().setPort(8080)).requestHandler(res -> {
  res.response().sendFile(webRoot + "/somefile.html");
 }).listen(onSuccess(res -> {
  vertx.createHttpClient(new HttpClientOptions()).request(HttpMethod.GET, 8080, "localhost", "/", onSuccess(resp -> {
   resp.bodyHandler(buff -> {
    assertTrue(buff.toString().startsWith("<html><body>blah</body></html>"));
    testComplete();
   });
  })).end();
 }));
 await();
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testTrustOptionsJson() throws Exception {
 PemTrustOptions options = new PemTrustOptions(new JsonObject());
 assertEquals(Collections.emptyList(), options.getCertPaths());
 assertEquals(Collections.emptyList(), options.getCertValues());
 String certPath = TestUtils.randomAlphaString(100);
 String certValue = TestUtils.randomAlphaString(100);
 JsonObject json = new JsonObject().
   put("certPaths", new JsonArray().add(certPath)).
   put("certValues", new JsonArray().add(certValue.getBytes()));
 options = new PemTrustOptions(json);
 assertEquals(Collections.singletonList(certPath), options.getCertPaths());
 assertEquals(Collections.singletonList(Buffer.buffer(certValue)), options.getCertValues());
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testContentDecompression() throws Exception {
 server.close();
 server = vertx.createHttpServer(new HttpServerOptions().setPort(DEFAULT_HTTP_PORT).setDecompressionSupported(true));
 String expected = TestUtils.randomAlphaString(1000);
 byte[] dataGzipped = TestUtils.compressGzip(expected);
 server.requestHandler(req -> {
  assertEquals("localhost:" + DEFAULT_HTTP_PORT, req.headers().get("host"));
  req.bodyHandler(buffer -> {
   assertEquals(expected, buffer.toString());
   req.response().end();
  });
 });
 server.listen(onSuccess(server -> {
  client
  .request(HttpMethod.POST, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "some-uri", onSuccess(resp -> testComplete()))
  .putHeader("Content-Encoding", "gzip")
  .end(Buffer.buffer(dataGzipped));
 }));
 await();
}

代码示例来源:origin: eclipse-vertx/vert.x

req.response().write(TestUtils.randomBuffer(numBytes));
 req.response().end();
});
Buffer totBuff = Buffer.buffer();
HttpClientRequest clientRequest = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, onSuccess(resp -> {
 resp.pause();
 paused.set(true);
 resp.handler(chunk -> {
  if (paused.get()) {
   fail("Shouldn't receive chunks when paused");
  } else {
   totBuff.appendBuffer(chunk);
 resp.endHandler(v -> {
  if (paused.get()) {
   fail("Shouldn't receive chunks when paused");
  } else {
   assertEquals(numWrites * numBytes, totBuff.length());
   testComplete();
}));
server.listen(onSuccess(s -> clientRequest.end()));

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testToJsonObject() throws Exception {
 JsonObject obj = new JsonObject();
 obj.put("wibble", "wibble_value");
 obj.put("foo", 5);
 obj.put("bar", true);
 Buffer buff = Buffer.buffer(obj.encode());
 assertEquals(obj, buff.toJsonObject());
 buff = Buffer.buffer(TestUtils.randomAlphaString(10));
 try {
  buff.toJsonObject();
  fail();
 } catch (DecodeException ignore) {
 }
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testSkipEncoding() throws Exception {
 serverWithMaxCompressionLevel.requestHandler(req -> {
  assertNotNull(req.headers().get("Accept-Encoding"));
  req.response()
   .putHeader(HttpHeaders.CONTENT_ENCODING, HttpHeaders.IDENTITY)
   .end(Buffer.buffer(COMPRESS_TEST_STRING).toString(CharsetUtil.UTF_8));
 });
 startServer(serverWithMaxCompressionLevel);
 clientraw.get(DEFAULT_HTTP_PORT + 1, DEFAULT_HTTP_HOST, "some-uri",
  onSuccess(resp -> {
   resp.bodyHandler(responseBuffer -> {
    String responseBody = responseBuffer.toString(CharsetUtil.UTF_8);
    assertEquals(COMPRESS_TEST_STRING, responseBody);
    testComplete();
   });
  })).putHeader(HttpHeaders.ACCEPT_ENCODING, HttpHeaders.DEFLATE_GZIP).end();
 await();
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testServerWebsocketSendPingExceeds125Bytes() {
 //Netty will prevent us from encoding a pingBody greater than 126 bytes by silently throwing an error in the background
 String pingBody = randomAlphaString(126);
 Integer maxFrameSize = 256;
 server = vertx.createHttpServer(new HttpServerOptions().setIdleTimeout(1).setPort(DEFAULT_HTTP_PORT).setHost(HttpTestBase.DEFAULT_HTTP_HOST).setMaxWebsocketFrameSize(maxFrameSize));
 server.websocketHandler(ws -> {
  ws.pongHandler(buff -> fail());
  ws.writeFrame(WebSocketFrame.pingFrame(Buffer.buffer(pingBody)));
  vertx.setTimer(2000, id -> testComplete());
 }).listen(onSuccess(v -> {
  client.websocket(DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, "/", ws -> {});
 }));
 await();
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testServerResponseWriteBufferFromOtherThread() throws Exception {
 server.requestHandler(req -> {
  runAsync(() -> {
   req.response().write("hello ").end("world");
  });
 }).listen(onSuccess(v -> {
  client.get(8080, "localhost", "/somepath", onSuccess(resp -> {
   assertEquals(200, resp.statusCode());
   resp.bodyHandler(buff -> {
    assertEquals(Buffer.buffer("hello world"), buff);
    testComplete();
   });
  })).exceptionHandler(this::fail).end();
 }));
 await();
}

代码示例来源:origin: eclipse-vertx/vert.x

private void testPost(String expected) throws Exception {
 Buffer content = Buffer.buffer();
 AtomicInteger count = new AtomicInteger();
 server.requestHandler(req -> {
  assertEquals(HttpMethod.POST, req.method());
  req.handler(buff -> {
   content.appendBuffer(buff);
   count.getAndIncrement();
  });
  req.endHandler(v -> {
   assertTrue(count.get() > 0);
   req.response().end();
  });
 });
 startServer();
 client.post(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath", onSuccess(resp -> {
  resp.endHandler(v -> {
   assertEquals(expected, content.toString());
   testComplete();
  });
 })).exceptionHandler(err -> {
  fail();
 }).end(expected);
 await();
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testCompressedResponseWithConnectionCloseAndNoCompressionHeader() throws Exception {
 Buffer expected = Buffer.buffer(TestUtils.randomAlphaString(2048));
 server.close();
 server = vertx.createHttpServer(new HttpServerOptions()
  .setPort(DEFAULT_HTTP_PORT)
  .setHost(DEFAULT_HTTP_HOST)
  .setCompressionSupported(true));
 server.requestHandler(req -> {
  req.response().end(expected);
 });
 startServer();
 client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, onSuccess(resp -> {
  resp.bodyHandler(buff -> {
   assertEquals(expected, buff);
   complete();
  });
 })).putHeader("Connection", "close")
  .exceptionHandler(this::fail)
  .end();
 await();
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testChunkedClientRequest() {
 server.requestHandler(req -> {
  HttpServerResponse resp = req.response();
  assertEquals("chunked", req.getHeader("transfer-encoding"));
  req.bodyHandler(body -> {
   assertEquals("the-chunk", body.toString());
   req.response().end();
  });
 }).listen(onSuccess(server -> {
  HttpClientRequest req = client.put(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/", res -> {
   testComplete();
  });
  req.setChunked(true);
  req.write("the-chunk");
  vertx.setTimer(1, id -> {
   req.end();
  });
 }));
 await();
}

代码示例来源:origin: eclipse-vertx/vert.x

private void testRequestBodyWrite(boolean chunked) {
 Buffer body = Buffer.buffer();
 server.requestHandler(req -> {
  req.bodyHandler(buffer -> {
   assertEquals(body, buffer);
   req.response().end();
  });
 });
 server.listen(onSuccess(server -> {
  HttpClientRequest req = client.request(HttpMethod.POST, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> testComplete());
  int numWrites = 10;
  int chunkSize = 100;
  if (chunked) {
   req.setChunked(true);
  } else {
   req.headers().set("Content-Length", String.valueOf(numWrites * chunkSize));
  }
  for (int i = 0; i < numWrites; i++) {
   Buffer b = TestUtils.randomBuffer(chunkSize);
   body.appendBuffer(b);
   req.write(b);
  }
  req.end();
 }));
 await();
}

代码示例来源:origin: eclipse-vertx/vert.x

private void testResponseBody(String expected) throws Exception {
 server.requestHandler(req -> {
  HttpServerResponse resp = req.response();
  resp.end(expected);
 });
 startServer();
 client.get(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath", onSuccess(resp -> {
  AtomicInteger count = new AtomicInteger();
  Buffer content = Buffer.buffer();
  resp.handler(buff -> {
   content.appendBuffer(buff);
   count.incrementAndGet();
  });
  resp.endHandler(v -> {
   assertTrue(count.get() > 0);
   assertEquals(expected, content.toString());
   testComplete();
  });
 }))
   .exceptionHandler(err -> fail())
   .end();
 await();
}

相关文章