Java Code Examples for io.vertx.core.net.NetSocket#write()

The following examples show how to use io.vertx.core.net.NetSocket#write() . 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: SecureScuttlebuttVertxClient.java    From incubator-tuweni with Apache License 2.0 6 votes vote down vote up
NetSocketClientHandler(
    NetSocket socket,
    Signature.PublicKey remotePublicKey,
    ClientHandlerFactory<T> handlerFactory,
    CompletableAsyncResult<T> completionHandle) {
  this.socket = socket;
  this.handshakeClient = SecureScuttlebuttHandshakeClient.create(keyPair, networkIdentifier, remotePublicKey);
  this.handlerFactory = handlerFactory;
  this.completionHandle = completionHandle;
  socket.closeHandler(res -> {
    if (handler != null) {
      handler.streamClosed();
    }
  });
  socket.exceptionHandler(e -> logger.error(e.getMessage(), e));
  socket.handler(this::handle);
  socket.write(Buffer.buffer(handshakeClient.createHello().toArrayUnsafe()));
}
 
Example 2
Source File: SecureScuttlebuttVertxClient.java    From cava with Apache License 2.0 6 votes vote down vote up
NetSocketClientHandler(
    Logger logger,
    NetSocket socket,
    Signature.PublicKey remotePublicKey,
    ClientHandlerFactory<T> handlerFactory,
    CompletableAsyncResult<T> completionHandle) {
  this.logger = logger;
  this.socket = socket;
  this.handshakeClient = SecureScuttlebuttHandshakeClient.create(keyPair, networkIdentifier, remotePublicKey);
  this.handlerFactory = handlerFactory;
  this.completionHandle = completionHandle;
  socket.closeHandler(res -> {
    if (handler != null) {
      handler.streamClosed();
    }
  });
  socket.exceptionHandler(e -> logger.error(e.getMessage(), e));
  socket.handler(this::handle);
  socket.write(Buffer.buffer(handshakeClient.createHello().toArrayUnsafe()));
}
 
Example 3
Source File: NetControl.java    From vertx-in-action with MIT License 6 votes vote down vote up
private void handleBuffer(NetSocket socket, Buffer buffer) {
  String command = buffer.toString();
  switch (command) {
    case "/list":
      listCommand(socket);
      break;
    case "/play":
      vertx.eventBus().send("jukebox.play", "");
      break;
    case "/pause":
      vertx.eventBus().send("jukebox.pause", "");
      break;
    default:
      if (command.startsWith("/schedule ")) {
        schedule(command);
      } else {
        socket.write("Unknown command\n");
      }
  }
}
 
Example 4
Source File: ProtocolGateway.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
void handleConnect(final NetSocket socket) {

        final Map<String, Object> dict = new HashMap<>();
        final RecordParser commandParser = RecordParser.newDelimited("\n", socket);
        commandParser.endHandler(end -> socket.close());
        commandParser.exceptionHandler(t -> {
            LOG.debug("error processing data from device", t);
            socket.close();
        });
        commandParser.handler(data -> handleData(socket, dict, data));
        socket.closeHandler(remoteClose -> {
            LOG.debug("device closed connection");
            Optional.ofNullable((CommandConsumer) dict.get(KEY_COMMAND_CONSUMER))
                .ifPresent(c -> {
                    c.close(res -> {
                        LOG.debug("closed device's command consumer");
                    });
                });
            socket.close();
        });

        socket.write(String.format("Welcome to the Protocol Gateway for devices of tenant [%s], please enter a command\n", tenant));
        LOG.debug("connection with client established");
    }
 
Example 5
Source File: ProtocolGateway.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Subscribes to commands for a device.
 *
 * @param deviceId The device to subscribe for.
 * @param socket The socket to use for sending commands to the device.
 * @return A future indicating the outcome.
 */
private Future<?> subscribe(final String deviceId, final NetSocket socket) {

    final Consumer<Message> messageHandler = m -> {

        final String commandPayload = MessageHelper.getPayloadAsString(m);
        final boolean isOneWay = m.getReplyTo() == null;
        if (isOneWay) {
            LOG.debug("received one-way command [name: {}]: {}", m.getSubject(), commandPayload);
            socket.write(String.format("ONE-WAY COMMAND [name: %s]: %s\n", m.getSubject(), commandPayload));
        } else {
            LOG.debug("received command [name: {}]: {}", m.getSubject(), commandPayload);
            if ("tellTime".equals(m.getSubject())) {
                respondWithTime(m).onComplete(sendAttempt -> {
                    if (sendAttempt.succeeded()) {
                        LOG.debug("sent response to command [name: {}, outcome: {}]", m.getSubject(), sendAttempt.result().getRemoteState().getType());
                    } else {
                        LOG.info("failed to send response to command [name: {}]", m.getSubject(), sendAttempt.cause());
                    }
                });
            }
        }
    };
    return amqpAdapterClientFactory.createDeviceSpecificCommandConsumer(deviceId, messageHandler);
}
 
Example 6
Source File: FrameHandlerTest.java    From vertx-stomp with Apache License 2.0 6 votes vote down vote up
@Test
public void testFrameHandlerWithInvalidFramesReceivedByServer() throws InterruptedException {
  AtomicReference<StompClientConnection> reference = new AtomicReference<>();

  client.connect(connection -> {
    reference.set(connection.result());
  });

  await().atMost(10, TimeUnit.SECONDS).until(() ->
      containsFrameWithCommand(receivedByServer, Frame.Command.CONNECT));
  await().atMost(10, TimeUnit.SECONDS).until(() ->
      containsFrameWithCommand(receivedByClient, Frame.Command.CONNECTED));

  StompClientConnectionImpl impl = (StompClientConnectionImpl) reference.get();
  NetSocket socket = impl.socket();

  socket.write(UNKNOWN_FRAME);

  await().atMost(10, TimeUnit.SECONDS).until(() ->
      containsFrameWithCommand(receivedByServer, Frame.Command.UNKNOWN));

  Frame frame = getFrameWithCommand(receivedByServer, Frame.Command.UNKNOWN);
  assertThat(frame).isNotNull();
  assertThat(frame.getHeader(Frame.STOMP_FRAME_COMMAND)).isEqualToIgnoringCase("YEAH");
}
 
Example 7
Source File: StratumServer.java    From besu with Apache License 2.0 5 votes vote down vote up
private void handle(final NetSocket socket) {
  StratumConnection conn =
      new StratumConnection(
          protocols, socket::close, bytes -> socket.write(Buffer.buffer(bytes)));
  socket.handler(conn::handleBuffer);
  socket.closeHandler(conn::close);
}
 
Example 8
Source File: ProtocolGateway.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private Future<Void> login(final String args, final NetSocket socket, final Map<String, Object> dictionary) {
    if (Strings.isNullOrEmpty(args)) {
        return Future.failedFuture("missing device identifier");
    } else {
        final String deviceId = args;
        LOG.info("authenticating device [id: {}]", deviceId);
        dictionary.put(KEY_DEVICE_ID, deviceId);
        socket.write(String.format("device [%s] logged in\n", deviceId));
        return Future.succeededFuture();
    }
}
 
Example 9
Source File: TestSmtpServer.java    From vertx-mail-client with Apache License 2.0 4 votes vote down vote up
private void writeResponses(NetSocket socket, String[] responses) {
  for (String line: responses) {
    log.debug("S:" + line);
    socket.write(line + "\r\n");
  }
}