io.vertx.core.net.NetServer Java Examples

The following examples show how to use io.vertx.core.net.NetServer. 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: TcpServerProvider.java    From jetlinks-community with Apache License 2.0 6 votes vote down vote up
private void initTcpServer(VertxTcpServer tcpServer, TcpServerProperties properties) {
    int instance = Math.max(2, properties.getInstance());
    List<NetServer> instances = new ArrayList<>(instance);
    for (int i = 0; i < instance; i++) {
        instances.add(vertx.createNetServer(properties.getOptions()));
    }
    payloadParserBuilder.build(properties.getParserType(), properties);
    tcpServer.setParserSupplier(() -> payloadParserBuilder.build(properties.getParserType(), properties));
    tcpServer.setServer(instances);
    tcpServer.setKeepAliveTimeout(properties.getLong("keepAliveTimeout", Duration.ofMinutes(10).toMillis()));
    for (NetServer netServer : instances) {
        netServer.listen(properties.createSocketAddress(), result -> {
            if (result.succeeded()) {
                log.info("tcp server startup on {}", result.result().actualPort());
            } else {
                log.error("startup tcp server error", result.cause());
            }
        });
    }
}
 
Example #2
Source File: MQTTBroker.java    From vertx-mqtt-broker with Apache License 2.0 6 votes vote down vote up
private void startTcpServer(ConfigParser c) {
    int port = c.getPort();
    String keyPath = c.getTlsKeyPath();
    String certPath = c.getTlsCertPath();
    boolean tlsEnabled = c.isTlsEnabled();
    int idleTimeout = c.getSocketIdleTimeout();

    // MQTT over TCP
    NetServerOptions opt = new NetServerOptions()
            .setTcpKeepAlive(true)
            .setIdleTimeout(idleTimeout) // in seconds; 0 means "don't timeout".
            .setPort(port);

    if(tlsEnabled) {
        opt.setSsl(true).setPemKeyCertOptions(new PemKeyCertOptions()
            .setKeyPath(keyPath)
            .setCertPath(certPath)
        );
    }
    NetServer netServer = vertx.createNetServer(opt);
    Map<String, MQTTSession> sessions = new MonitoredMap<>();
    netServer.connectHandler(netSocket -> {
        MQTTNetSocket mqttNetSocket = new MQTTNetSocket(vertx, c, netSocket, sessions);
        mqttNetSocket.start();
    }).listen();
}
 
Example #3
Source File: TestTcpServer.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void testTcpServerNonSSL(@Mocked Vertx vertx, @Mocked AsyncResultCallback<InetSocketAddress> callback,
    @Mocked NetServer netServer) {
  new Expectations() {
    {
      vertx.createNetServer();
      result = netServer;
      netServer.connectHandler((Handler) any);
      netServer.listen(anyInt, anyString, (Handler) any);
    }
  };
  URIEndpointObject endpointObject = new URIEndpointObject("highway://127.0.0.1:6663");
  TcpServer server = new TcpServerForTest(endpointObject);
  // assert done in Expectations
  server.init(vertx, "", callback);
}
 
Example #4
Source File: TestTcpServer.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void testTcpServerSSL(@Mocked Vertx vertx, @Mocked AsyncResultCallback<InetSocketAddress> callback,
    @Mocked NetServer netServer) {
  new Expectations() {
    {
      vertx.createNetServer((NetServerOptions) any);
      result = netServer;
      netServer.connectHandler((Handler) any);
      netServer.listen(anyInt, anyString, (Handler) any);
    }
  };
  URIEndpointObject endpointObject = new URIEndpointObject("highway://127.0.0.1:6663?sslEnabled=true");
  TcpServer server = new TcpServerForTest(endpointObject);
  // assert done in Expectations
  server.init(vertx, "", callback);
}
 
Example #5
Source File: WebClientTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Repeat(times = 100)
@Test
public void testTimeoutRequestBeforeSending() throws Exception {
  NetServer server = vertx.createNetServer();
  server.connectHandler(so -> {
  });
  CountDownLatch latch = new CountDownLatch(1);
  server.listen(8080, "localhost", onSuccess(v -> {
    latch.countDown();
  }));
  awaitLatch(latch);
  webClient
    .get(8080, "localhost", "/")
    .timeout(1)
    .send(onFailure(err -> {
      testComplete();
    }));
  await();
}
 
Example #6
Source File: ProtonClientTest.java    From vertx-proton with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 20000)
public void testConnectionDisconnectedDuringCreation(TestContext context) {
  server.close();

  Async connectFailsAsync = context.async();

  NetServer netServer = this.vertx.createNetServer();
  netServer.connectHandler(netSocket -> {
    netSocket.pause();
    vertx.setTimer(50, x -> {
      netSocket.close();
    });
  });

  netServer.listen(listenResult -> {
    context.assertTrue(listenResult.succeeded());

    ProtonClient.create(vertx).connect("localhost", netServer.actualPort(), connResult -> {
      context.assertFalse(connResult.succeeded());
      connectFailsAsync.complete();
    });

  });

  connectFailsAsync.awaitSuccess();
}
 
Example #7
Source File: TcpServer.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Starts the server listening on the configured address and port.
 *
 * @return A future indicating the outcome.
 */
public Future<NetServer> start() {
    if (connectHandler == null) {
        LOG.warn("no connect handler set, server will reject all connections");
        connectHandler = socket -> socket.close();
    }
    final Promise<NetServer> result = Promise.promise();
    vertx.createNetServer()
        .connectHandler(connectHandler)
        .exceptionHandler(this::handleHandshakeException)
        .listen(config.getInsecurePort(6666), config.getInsecurePortBindAddress(), result);
    return result.future()
            .map(s -> {
                server = s;
                LOG.info("successfully started TCP server [address: {}, port: {}]", config.getInsecurePortBindAddress(), s.actualPort());
                return s;
            })
            .recover(t -> {
                LOG.error("failed to start TCP server [address: {}, port: {}]", config.getInsecurePortBindAddress(), config.getInsecurePort(6666), t);
                return Future.failedFuture(t);
            });
}
 
Example #8
Source File: VertxTcpServer.java    From jetlinks-community with Apache License 2.0 5 votes vote down vote up
public void setServer(Collection<NetServer> mqttServer) {
    if (this.tcpServers != null && !this.tcpServers.isEmpty()) {
        shutdown();
    }
    this.tcpServers = mqttServer;

    for (NetServer tcpServer : this.tcpServers) {
        tcpServer.connectHandler(this::acceptTcpConnection);
    }

}
 
Example #9
Source File: AuthorizationTests.java    From vertx-mqtt-broker with Apache License 2.0 5 votes vote down vote up
private NetServer startTcpBroker(JsonObject conf) {

		ConfigParser c = new ConfigParser(conf);

		NetServerOptions opt = new NetServerOptions().setTcpKeepAlive(true)
				.setIdleTimeout(conf.getInteger("socket_idle_timeout")).setPort(conf.getInteger("tcp_port"));

		NetServer netServer = vertx.createNetServer(opt);
		netServer.connectHandler(netSocket -> {
			Map<String, MQTTSession> sessions = new HashMap<>();
			MQTTNetSocket mqttNetSocket = new MQTTNetSocket(vertx, c, netSocket, sessions);
			mqttNetSocket.start();
		}).listen();
		return netServer;
	}
 
Example #10
Source File: MetricsTestBase.java    From vertx-dropwizard-metrics with Apache License 2.0 5 votes vote down vote up
protected void cleanup(NetServer server) throws Exception {
  CountDownLatch latch = new CountDownLatch(1);
  if (server != null) {
    server.close(ar -> {
      latch.countDown();
    });
  }
  awaitLatch(latch);
}
 
Example #11
Source File: MetricsTestBase.java    From vertx-dropwizard-metrics with Apache License 2.0 5 votes vote down vote up
protected NetServer createNetServer(NetServerOptions options) {
  NetServer server = vertx.createNetServer(options);
  toClose.add(() -> {
    CountDownLatch latch = new CountDownLatch(1);
    server.close(ar -> {
      latch.countDown();
    });
    awaitLatch(latch);
    return null;
  });
  return server;
}
 
Example #12
Source File: ProtonServerImpl.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
private Handler<AsyncResult<NetServer>> convertHandler(final Handler<AsyncResult<ProtonServer>> handler) {
  return result -> {
    if (result.succeeded()) {
      handler.handle(Future.succeededFuture(ProtonServerImpl.this));
    } else {
      handler.handle(Future.failedFuture(result.cause()));
    }
  };
}
 
Example #13
Source File: VertxNetServer.java    From Lealone-Plugins with Apache License 2.0 5 votes vote down vote up
private NetServer getNetServer() {
    NetServerOptions nso;
    if (ssl) {
        ServerEncryptionOptions options = getServerEncryptionOptions();
        nso = VertxNetUtils.getNetServerOptions(options);
    } else {
        nso = VertxNetUtils.getNetServerOptions(null);
    }
    nso.setHost(host);
    nso.setPort(port);
    NetServer server = vertx.createNetServer(nso);
    return server;
}
 
Example #14
Source File: StompServerImpl.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance of {@link StompServerImpl}.
 * @param vertx the vert.x instance
 * @param net the net server, may be {@code null}
 * @param options the options
 */
public StompServerImpl(Vertx vertx, NetServer net, StompServerOptions options) {
  Objects.requireNonNull(vertx);
  Objects.requireNonNull(options);
  this.options = options;
  this.vertx = vertx;
  if (net == null) {
    server = vertx.createNetServer(options);
  } else {
    server = net;
  }
}
 
Example #15
Source File: ProcessModuleHandleTest.java    From okapi with Apache License 2.0 5 votes vote down vote up
@Test
public void testPortAlreadyInUse(TestContext context) {
  final Async async = context.async();

  final NetServer ns = vertx.createNetServer().connectHandler( res -> { res.close(); });
  ns.listen(9231, res -> {
    if (res.failed()) {
      async.complete();
      ns.close();
    } else {
      LaunchDescriptor desc = new LaunchDescriptor();
      desc.setExec("java " + testModuleArgs);
      ModuleHandle mh = createModuleHandle(desc, 9231);
      mh.start(res1 -> {
        context.assertTrue(res1.failed());
        context.assertEquals("port 9231 already in use", res1.cause().getMessage());
        ns.close();
        // stop is not necessary, but check that we can call it anyway
        mh.stop(res2 -> {
          context.assertTrue(res2.succeeded());
          async.complete();
        });
      });
    }
  });

}
 
Example #16
Source File: VertxTcpServer.java    From jetlinks-community with Apache License 2.0 5 votes vote down vote up
@Override
public void shutdown() {
    if (null != tcpServers) {
        for (NetServer tcpServer : tcpServers) {
            execute(tcpServer::close);
        }
        tcpServers = null;
    }
}
 
Example #17
Source File: StompServerExamples.java    From vertx-stomp with Apache License 2.0 4 votes vote down vote up
public void example5(Vertx vertx, NetServer netServer) {
  Future<StompServer> server = StompServer.create(vertx, netServer)
      .handler(StompServerHandler.create(vertx))
      .listen();
}
 
Example #18
Source File: VertxNetUtils.java    From Lealone-Plugins with Apache License 2.0 4 votes vote down vote up
public static NetServer createNetServer(Vertx vertx, EncryptionOptions eo) {
    NetServerOptions netServerOptions = VertxNetUtils.getNetServerOptions(eo);
    NetServer server = vertx.createNetServer(netServerOptions);
    return server;
}
 
Example #19
Source File: Proxy.java    From vertx-mqtt with Apache License 2.0 4 votes vote down vote up
/**
 * Start the proxy
 *
 * @param startHandler  handler to call when starting is completed
 */
public void start(Handler<AsyncResult<Void>> startHandler) {

  this.server = this.vertx.createNetServer();
  this.client = this.vertx.createNetClient();

  // handling incoming connection from the MQTT client
  this.server.connectHandler(socket -> {

    this.serverSocket = socket;

    // handling message from the MQTT client to the MQTT server
    this.serverSocket.handler(buffer -> {

      if (!this.paused) {

        log.info(String.format("%s:%d ---> %s:%d",
          this.clientSocket.localAddress().host(),
          this.clientSocket.localAddress().port(),
          this.clientSocket.remoteAddress().host(),
          this.clientSocket.remoteAddress().port()));

        this.clientSocket.write(buffer);
      }
    });

    // if MQTT client closes connection THEN close connection with MQTT server
    this.serverSocket.closeHandler(v -> {
      this.clientSocket.close();
    });
  });

  Promise<NetServer> serverPromise = Promise.promise();
  this.server.listen(SERVER_PORT, SERVER_HOST, serverPromise);

  Promise<NetSocket> clientPromise = Promise.promise();
  this.client.connect(this.mqttServerPort, this.mqttServerHost, clientPromise);

  CompositeFuture.all(serverPromise.future(), clientPromise.future()).onComplete(ar -> {

    // server started and client connected successfully
    if (ar.succeeded()) {

      log.info(String.format("Proxy server started on port %d", serverPromise.future().result().actualPort()));

      this.clientSocket = clientPromise.future().result();

      log.info(String.format("Proxy client connected to %s:%d",
        this.clientSocket.remoteAddress().host(),
        this.clientSocket.remoteAddress().port()));

      // handling message from the MQTT server to the MQTT client
      this.clientSocket.handler(buffer -> {

        log.info(String.format("%s:%d <--- %s:%d",
          this.serverSocket.localAddress().host(),
          this.serverSocket.localAddress().port(),
          this.serverSocket.remoteAddress().host(),
          this.serverSocket.remoteAddress().port()));

        this.serverSocket.write(buffer);
      });

      // if MQTT server closes connection THEN close connection with MQTT client
      this.clientSocket.closeHandler(v -> {
        this.serverSocket.close();
      });

      startHandler.handle(Future.succeededFuture());

    } else {

      if (!serverPromise.future().succeeded())
        log.info("Error starting proxy server", serverPromise.future().cause());

      if (!clientPromise.future().succeeded())
        log.info("Error connecting proxy client", clientPromise.future().cause());

      startHandler.handle(Future.failedFuture(ar.cause()));
    }
  });

}
 
Example #20
Source File: SfsVertxImpl.java    From sfs with Apache License 2.0 4 votes vote down vote up
@Override
public NetServer createNetServer() {
    return vertx.createNetServer();
}
 
Example #21
Source File: MetricsTestBase.java    From vertx-dropwizard-metrics with Apache License 2.0 4 votes vote down vote up
protected NetServer createNetServer() {
  return createNetServer(new HttpServerOptions());
}
 
Example #22
Source File: SfsVertxImpl.java    From sfs with Apache License 2.0 4 votes vote down vote up
@Override
public NetServer createNetServer(NetServerOptions options) {
    return vertx.createNetServer(options);
}
 
Example #23
Source File: TestTcpServer.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void testConnectionLimit(@Mocked Vertx vertx, @Mocked AsyncResultCallback<InetSocketAddress> callback,
    @Mocked NetServer netServer, @Mocked NetSocketImpl netSocket) {
  DefaultServerEndpointMetric endpointMetric = new DefaultServerEndpointMetric(null);
  DefaultTcpServerMetrics tcpServerMetrics = new DefaultTcpServerMetrics(endpointMetric);

  new MockUp<NetServer>(netServer) {
    @Mock
    NetServer connectHandler(Handler<NetSocket> handler) {
      connectHandler = handler;
      return netServer;
    }
  };
  new MockUp<NetSocketImpl>(netSocket) {
    @Mock
    void close() {
      netSocketClosed = true;
    }
  };
  new Expectations() {
    {
      vertx.createNetServer((NetServerOptions) any);
      result = netServer;
      netServer.listen(anyInt, anyString, (Handler) any);
      netSocket.metrics();
      result = tcpServerMetrics;
    }
  };
  URIEndpointObject endpointObject = new URIEndpointObject("highway://127.0.0.1:6663?sslEnabled=true");
  TcpServer server = new TcpServerForTest(endpointObject) {
    @Override
    protected int getConnectionLimit() {
      return 2;
    }
  };
  // assert done in Expectations
  server.init(vertx, "", callback);

  // no problem
  endpointMetric.onConnect();
  endpointMetric.onConnect();
  connectHandler.handle(netSocket);

  // reject
  endpointMetric.onConnect();
  connectHandler.handle(netSocket);
  Assert.assertTrue(netSocketClosed);
  Assert.assertEquals(1, endpointMetric.getRejectByConnectionLimitCount());
}
 
Example #24
Source File: TcpServer.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
public void init(Vertx vertx, String sslKey, AsyncResultCallback<InetSocketAddress> callback) {
  NetServer netServer;
  if (endpointObject.isSslEnabled()) {
    SSLOptionFactory factory =
        SSLOptionFactory.createSSLOptionFactory(sslKey, null);
    SSLOption sslOption;
    if (factory == null) {
      sslOption = SSLOption.buildFromYaml(sslKey);
    } else {
      sslOption = factory.createSSLOption();
    }
    SSLCustom sslCustom = SSLCustom.createSSLCustom(sslOption.getSslCustomClass());
    NetServerOptions serverOptions = new NetServerOptions();
    VertxTLSBuilder.buildNetServerOptions(sslOption, sslCustom, serverOptions);
    netServer = vertx.createNetServer(serverOptions);
  } else {
    netServer = vertx.createNetServer();
  }

  netServer.connectHandler(netSocket -> {
    DefaultTcpServerMetrics serverMetrics = (DefaultTcpServerMetrics) ((NetSocketImpl) netSocket).metrics();
    DefaultServerEndpointMetric endpointMetric = serverMetrics.getEndpointMetric();
    long connectedCount = endpointMetric.getCurrentConnectionCount();
    int connectionLimit = getConnectionLimit();
    if (connectedCount > connectionLimit) {
      netSocket.close();
      endpointMetric.onRejectByConnectionLimit();
      return;
    }

    TcpServerConnection connection = createTcpServerConnection();
    connection.init(netSocket);
  });
  netServer.exceptionHandler(e -> {
    LOGGER.error("Unexpected error in server.{}", ExceptionUtils.getExceptionMessageWithoutTrace(e));
  });
  InetSocketAddress socketAddress = endpointObject.getSocketAddress();
  netServer.listen(socketAddress.getPort(), socketAddress.getHostString(), ar -> {
    if (ar.succeeded()) {
      callback.success(socketAddress);
      return;
    }

    // 监听失败
    String msg = String.format("listen failed, address=%s", socketAddress.toString());
    callback.fail(new Exception(msg, ar.cause()));
  });
}
 
Example #25
Source File: StompServer.java    From vertx-stomp with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a {@link StompServer} based on the default Stomp Server implementation.
 *
 * @param vertx   the vert.x instance to use
 * @param net     the Net server used by the STOMP server
 * @param options the server options
 * @return the created {@link StompServer}
 */
static StompServer create(Vertx vertx, NetServer net, StompServerOptions options) {
  return new StompServerImpl(vertx, net, options);
}
 
Example #26
Source File: StompServer.java    From vertx-stomp with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a {@link StompServer} based on the default Stomp Server implementation.
 *
 * @param vertx     the vert.x instance to use
 * @param netServer the Net server used by the STOMP server
 * @return the created {@link StompServer}
 */
static StompServer create(Vertx vertx, NetServer netServer) {
  return new StompServerImpl(vertx, netServer, new StompServerOptions());
}