java.net.InetSocketAddress Java Examples

The following examples show how to use java.net.InetSocketAddress. 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: TCPFiberProxy.java    From loom-fiber with MIT License 6 votes vote down vote up
@SuppressWarnings("resource")
public static void main(String[] args) throws IOException {
  var server = ServerSocketChannel.open();
  server.bind(new InetSocketAddress(7777));
  System.out.println("server bound to " + server.getLocalAddress());
  
  var remote = SocketChannel.open();
  remote.connect(new InetSocketAddress(InetAddress.getByName(Host.NAME), 7));
  //remote.configureBlocking(false);
  
  System.out.println("accepting ...");
  var client = server.accept();
  //client.configureBlocking(false);
  
  var executor = Executors.newSingleThreadExecutor();
  //var executor = ForkJoinPool.commonPool();
  Thread.builder().virtual(executor).task(runnable(client, remote)).start();
  Thread.builder().virtual(executor).task(runnable(remote, client)).start();
}
 
Example #2
Source File: PcepChannelHandler.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    channel = e.getChannel();
    log.info("PCC connected from {}", channel.getRemoteAddress());

    address = channel.getRemoteAddress();
    if (!(address instanceof InetSocketAddress)) {
        throw new IOException("Invalid peer connection.");
    }

    inetAddress = (InetSocketAddress) address;
    peerAddr = IpAddress.valueOf(inetAddress.getAddress()).toString();

    // Wait for open message from pcc client
    setState(ChannelState.OPENWAIT);
    controller.peerStatus(peerAddr, PcepCfg.State.OPENWAIT.toString(), sessionId);
}
 
Example #3
Source File: TestOmUtils.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetOmHAAddressesById() {
  OzoneConfiguration conf = new OzoneConfiguration();
  conf.set(OZONE_OM_SERVICE_IDS_KEY, "ozone1");
  conf.set("ozone.om.nodes.ozone1", "node1,node2,node3");
  conf.set("ozone.om.address.ozone1.node1", "1.1.1.1");
  conf.set("ozone.om.address.ozone1.node2", "1.1.1.2");
  conf.set("ozone.om.address.ozone1.node3", "1.1.1.3");
  Map<String, List<InetSocketAddress>> addresses =
      OmUtils.getOmHAAddressesById(conf);
  assertFalse(addresses.isEmpty());
  List<InetSocketAddress> rpcAddrs = addresses.get("ozone1");
  assertFalse(rpcAddrs.isEmpty());
  assertTrue(rpcAddrs.stream().anyMatch(
      a -> a.getAddress().getHostAddress().equals("1.1.1.1")));
  assertTrue(rpcAddrs.stream().anyMatch(
      a -> a.getAddress().getHostAddress().equals("1.1.1.2")));
  assertTrue(rpcAddrs.stream().anyMatch(
      a -> a.getAddress().getHostAddress().equals("1.1.1.3")));
}
 
Example #4
Source File: PulsarServiceNameResolverTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleHostUrl() throws Exception {
    String serviceUrl = "pulsar://host1:6650";
    resolver.updateServiceUrl(serviceUrl);
    assertEquals(serviceUrl, resolver.getServiceUrl());
    assertEquals(ServiceURI.create(serviceUrl), resolver.getServiceUri());

    InetSocketAddress expectedAddress = InetSocketAddress.createUnresolved("host1", 6650);
    assertEquals(expectedAddress, resolver.resolveHost());
    assertEquals(URI.create(serviceUrl), resolver.resolveHostUri());

    String newServiceUrl = "pulsar://host2:6650";
    resolver.updateServiceUrl(newServiceUrl);
    assertEquals(newServiceUrl, resolver.getServiceUrl());
    assertEquals(ServiceURI.create(newServiceUrl), resolver.getServiceUri());

    InetSocketAddress newExpectedAddress = InetSocketAddress.createUnresolved("host2", 6650);
    assertEquals(newExpectedAddress, resolver.resolveHost());
    assertEquals(URI.create(newServiceUrl), resolver.resolveHostUri());
}
 
Example #5
Source File: EchoTest.java    From jdk-source-analysis with Apache License 2.0 6 votes vote down vote up
@Test
public void testClient() throws InterruptedException {
  NioEventLoopGroup group = new NioEventLoopGroup();
  try {
    Bootstrap b = new Bootstrap();
    b.group(group)
      .channel(NioSocketChannel.class)
      .remoteAddress(new InetSocketAddress("localhost", PORT))
      .handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
          ch.pipeline().addLast(new EchoClientHandler());
        }
      });
    ChannelFuture f = b.connect().sync();
    f.channel().closeFuture().sync();
  } finally {
    group.shutdownGracefully().sync();
  }
}
 
Example #6
Source File: RpcTest.java    From java-core-learning-example with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    // 启动服务提供者
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                RpcExporter.exporter("localhost",8088);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();

    // 创建服务本地代理
    RpcImporter<EchoService> importer = new RpcImporter<>();

    // 从服务本地代理获取服务对象类
    EchoService echo = importer.importer(EchoServiceImpl.class,new InetSocketAddress("localhost",8088));
    System.out.println(echo.echo("Are you OK?"));
}
 
Example #7
Source File: ProxyDetectorImplTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void override_hostPort() throws Exception {
  final String overrideHost = "10.99.99.99";
  final int overridePort = 1234;
  final String overrideHostWithPort = overrideHost + ":" + overridePort;
  ProxyDetectorImpl proxyDetector = new ProxyDetectorImpl(
      proxySelectorSupplier,
      authenticator,
      overrideHostWithPort);
  ProxyParameters detected = proxyDetector.proxyFor(destination);
  assertNotNull(detected);
  assertEquals(
      new ProxyParameters(
          new InetSocketAddress(InetAddress.getByName(overrideHost), overridePort),
          NO_USER,
          NO_PW),
      detected);
}
 
Example #8
Source File: HttpConnectHarCaptureFilter.java    From CapturePacket with MIT License 6 votes vote down vote up
public HttpConnectHarCaptureFilter(HttpRequest originalRequest, ChannelHandlerContext ctx, Har har, String currentPageRef) {
    super(originalRequest, ctx);

    if (har == null) {
        throw new IllegalStateException("Attempted har capture when har is null");
    }

    if (!ProxyUtils.isCONNECT(originalRequest)) {
        throw new IllegalStateException("Attempted HTTP CONNECT har capture on non-HTTP CONNECT request");
    }

    this.har = har;
    this.currentPageRef = currentPageRef;

    this.clientAddress = (InetSocketAddress) ctx.channel().remoteAddress();

    // create and cache an HTTP CONNECT timing object to capture timing-related information
    this.httpConnectTiming = new HttpConnectTiming();
    httpConnectTimes.put(clientAddress, httpConnectTiming);
}
 
Example #9
Source File: TcpProxyServer.java    From BaoLianDeng with GNU General Public License v3.0 6 votes vote down vote up
InetSocketAddress getDestAddress(SocketChannel localChannel) {
    short portKey = (short) localChannel.socket().getPort();
    NatSession session = NatSessionManager.getSession(portKey);
    if (session != null) {
        if (ProxyConfig.Instance.needProxy(session.RemoteIP)) {
            if (ProxyConfig.IS_DEBUG)
                Log.d(Constant.TAG, String.format("%d/%d:[PROXY] %s=>%s:%d", NatSessionManager.getSessionCount(),
                        Tunnel.SessionCount, session.RemoteHost,
                        CommonMethods.ipIntToString(session.RemoteIP), session.RemotePort & 0xFFFF));
            return InetSocketAddress.createUnresolved(session.RemoteHost, session.RemotePort & 0xFFFF);
        } else {
            return new InetSocketAddress(localChannel.socket().getInetAddress(), session.RemotePort & 0xFFFF);
        }
    }
    return null;
}
 
Example #10
Source File: NetworkUtils.java    From incubator-heron with Apache License 2.0 6 votes vote down vote up
/**
 * Tests if a network location is reachable. This is best effort and may give false
 * not reachable.
 *
 * @param endpoint the endpoint to connect to
 * @param timeout Open connection will wait for this timeout.
 * @param retryCount In case of connection timeout try retryCount times.
 * @param retryInterval the interval to retryCount
 * @return true if the network location is reachable
 */
public static boolean isLocationReachable(
    InetSocketAddress endpoint,
    Duration timeout,
    int retryCount,
    Duration retryInterval) {
  int retryLeft = retryCount;
  while (retryLeft > 0) {
    try (Socket s = new Socket()) {
      s.connect(endpoint, (int) timeout.toMillis());
      return true;
    } catch (IOException e) {
    } finally {
      SysUtils.sleep(retryInterval);
      retryLeft--;
    }
  }
  LOG.log(Level.FINE, "Failed to connect to: {0}", endpoint.toString());
  return false;
}
 
Example #11
Source File: AsynchronousServerSocketChannelImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Override
public final AsynchronousServerSocketChannel bind(SocketAddress local, int backlog)
    throws IOException
{
    InetSocketAddress isa = (local == null) ? new InetSocketAddress(0) :
        Net.checkAddress(local);
    SecurityManager sm = System.getSecurityManager();
    if (sm != null)
        sm.checkListen(isa.getPort());

    try {
        begin();
        synchronized (stateLock) {
            if (localAddress != null)
                throw new AlreadyBoundException();
            NetHooks.beforeTcpBind(fd, isa.getAddress(), isa.getPort());
            Net.bind(fd, isa.getAddress(), isa.getPort());
            Net.listen(fd, backlog < 1 ? 50 : backlog);
            localAddress = Net.localAddress(fd);
        }
    } finally {
        end();
    }
    return this;
}
 
Example #12
Source File: UndertowServerRuntimeInfo.java    From digdag with Apache License 2.0 6 votes vote down vote up
void addListenAddress(final String name, final InetSocketAddress socketAddress)
{
    addresses.add(
            new GuiceRsServerRuntimeInfo.ListenAddress()
            {
                @Override
                public String getName()
                {
                    return name;
                }

                @Override
                public InetSocketAddress getSocketAddress()
                {
                    return socketAddress;
                }
            });
}
 
Example #13
Source File: FlushStrategyOverrideTest.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    service = new FlushingService();
    serverCtx = HttpServers.forAddress(localAddress(0))
            .ioExecutor(ctx.ioExecutor())
            .executionStrategy(noOffloadsStrategy())
            .listenStreaming(service)
            .toFuture().get();
    InetSocketAddress serverAddr = (InetSocketAddress) serverCtx.listenAddress();
    client = forSingleAddress(new NoopSD(serverAddr), serverAddr)
            .disableHostHeaderFallback()
            .ioExecutor(ctx.ioExecutor())
            .executionStrategy(noOffloadsStrategy())
            .unresolvedAddressToHost(InetSocketAddress::getHostString)
            .buildStreaming();
    conn = client.reserveConnection(client.get("/")).toFuture().get();
}
 
Example #14
Source File: MiniCluster.java    From flink with Apache License 2.0 6 votes vote down vote up
public CompletableFuture<JobSubmissionResult> submitJob(JobGraph jobGraph) {
	final CompletableFuture<DispatcherGateway> dispatcherGatewayFuture = getDispatcherGatewayFuture();

	// we have to allow queued scheduling in Flip-6 mode because we need to request slots
	// from the ResourceManager
	jobGraph.setAllowQueuedScheduling(true);

	final CompletableFuture<InetSocketAddress> blobServerAddressFuture = createBlobServerAddress(dispatcherGatewayFuture);

	final CompletableFuture<Void> jarUploadFuture = uploadAndSetJobFiles(blobServerAddressFuture, jobGraph);

	final CompletableFuture<Acknowledge> acknowledgeCompletableFuture = jarUploadFuture
		.thenCombine(
			dispatcherGatewayFuture,
			(Void ack, DispatcherGateway dispatcherGateway) -> dispatcherGateway.submitJob(jobGraph, rpcTimeout))
		.thenCompose(Function.identity());

	return acknowledgeCompletableFuture.thenApply(
		(Acknowledge ignored) -> new JobSubmissionResult(jobGraph.getJobID()));
}
 
Example #15
Source File: FakeRemoteServer.java    From openwebbeans-meecrowave with Apache License 2.0 6 votes vote down vote up
@Override
public Statement apply(final Statement statement, final Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            try {
                server = HttpServer.create(new InetSocketAddress(0), 0);
                configurers.forEach(it -> it.accept(server, (exchange, status, payload) -> {
                    exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, payload.length);
                    try (final OutputStream os = exchange.getResponseBody()) {
                        os.write(payload);
                    }
                }));
                server.start();
                System.setProperty("fake.server.port", Integer.toString(server.getAddress().getPort()));
                statement.evaluate();
            } finally {
                server.stop(0);
                server = null;
                System.clearProperty("fake.server.port");
            }
        }
    };
}
 
Example #16
Source File: AsyncSocketFactory.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T extends Closeable> T connect(String host, int port, PropertySet props, int loginTimeout) throws IOException {
    try {
        this.channel = AsynchronousSocketChannel.open();
        //channel.setOption(java.net.StandardSocketOptions.TCP_NODELAY, true);
        this.channel.setOption(java.net.StandardSocketOptions.SO_SNDBUF, 128 * 1024);
        this.channel.setOption(java.net.StandardSocketOptions.SO_RCVBUF, 128 * 1024);

        Future<Void> connectPromise = this.channel.connect(new InetSocketAddress(host, port));
        connectPromise.get();

    } catch (CJCommunicationsException e) {
        throw e;
    } catch (IOException | InterruptedException | ExecutionException | RuntimeException ex) {
        throw new CJCommunicationsException(ex);
    }
    return (T) this.channel;
}
 
Example #17
Source File: NioAsyncLoadBalanceClient.java    From nifi with Apache License 2.0 6 votes vote down vote up
private SocketChannel createChannel() throws IOException {
    final SocketChannel socketChannel = SocketChannel.open();
    try {
        socketChannel.configureBlocking(true);
        final Socket socket = socketChannel.socket();
        socket.setSoTimeout(timeoutMillis);

        socket.connect(new InetSocketAddress(nodeIdentifier.getLoadBalanceAddress(), nodeIdentifier.getLoadBalancePort()));
        socket.setSoTimeout(timeoutMillis);

        return socketChannel;
    } catch (final Exception e) {
        try {
            socketChannel.close();
        } catch (final Exception closeException) {
            e.addSuppressed(closeException);
        }

        throw e;
    }
}
 
Example #18
Source File: SocketOrChannelConnectionImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public SocketOrChannelConnectionImpl(ORB orb,
                                     CorbaContactInfo contactInfo,
                                     boolean useSelectThreadToWait,
                                     boolean useWorkerThread,
                                     String socketType,
                                     String hostname,
                                     int port)
{
    this(orb, useSelectThreadToWait, useWorkerThread);

    this.contactInfo = contactInfo;

    try {
        socket = orb.getORBData().getSocketFactory()
            .createSocket(socketType,
                          new InetSocketAddress(hostname, port));
        socketChannel = socket.getChannel();

        if (socketChannel != null) {
            boolean isBlocking = !useSelectThreadToWait;
            socketChannel.configureBlocking(isBlocking);
        } else {
            // IMPORTANT: non-channel-backed sockets must use
            // dedicated reader threads.
            setUseSelectThreadToWait(false);
        }
        if (orb.transportDebugFlag) {
            dprint(".initialize: connection created: " + socket);
        }
    } catch (Throwable t) {
        throw wrapper.connectFailure(t, socketType, hostname,
                                     Integer.toString(port));
    }
    state = OPENING;
}
 
Example #19
Source File: BlobClientTest.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Checks the correct result if a GET operation fails during the file download.
 *
 * @param jobId
 * 		job ID or <tt>null</tt> if job-unrelated
 * @param blobType
 * 		whether the BLOB should become permanent or transient
 */
private void testGetFailsDuringStreaming(@Nullable final JobID jobId, BlobKey.BlobType blobType)
		throws IOException {

	try (BlobClient client = new BlobClient(
		new InetSocketAddress("localhost", getBlobServer().getPort()), getBlobClientConfig())) {

		byte[] data = new byte[5000000];
		Random rnd = new Random();
		rnd.nextBytes(data);

		// put content addressable (like libraries)
		BlobKey key = client.putBuffer(jobId, data, 0, data.length, blobType);
		assertNotNull(key);

		// issue a GET request that succeeds
		InputStream is = client.getInternal(jobId, key);

		byte[] receiveBuffer = new byte[data.length];
		int firstChunkLen = 50000;
		BlobUtils.readFully(is, receiveBuffer, 0, firstChunkLen, null);
		BlobUtils.readFully(is, receiveBuffer, firstChunkLen, firstChunkLen, null);

		// shut down the server
		for (BlobServerConnection conn : getBlobServer().getCurrentActiveConnections()) {
			conn.close();
		}

		try {
			BlobUtils.readFully(is, receiveBuffer, 2 * firstChunkLen, data.length - 2 * firstChunkLen, null);
			// we tolerate that this succeeds, as the receiver socket may have buffered
			// everything already, but in this case, also verify the contents
			assertArrayEquals(data, receiveBuffer);
		}
		catch (IOException e) {
			// expected
		}
	}
}
 
Example #20
Source File: NettyStartTlsSMTPServerTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void startTlsShouldFailWhenFollowedByInjectedCommand() throws Exception {
    server = createServer(createProtocol(Optional.empty()), Encryption.createStartTls(BogusSslContextFactory.getServerContext()));
    smtpsClient = createClient();

    server.bind();
    InetSocketAddress bindedAddress = new ProtocolServerUtils(server).retrieveBindedAddress();
    smtpsClient.connect(bindedAddress.getAddress().getHostAddress(), bindedAddress.getPort());
    smtpsClient.sendCommand("EHLO localhost");

    smtpsClient.sendCommand("STARTTLS\r\nRSET\r\n");
    assertThat(SMTPReply.isPositiveCompletion(smtpsClient.getReplyCode())).isFalse();
}
 
Example #21
Source File: HttpTolerantApplicationTest.java    From datakernel with Apache License 2.0 5 votes vote down vote up
@Test
public void testTolerantServer() throws Exception {
	int port = getFreePort();

	Eventloop eventloop = Eventloop.create().withFatalErrorHandler(rethrowOnAnyError());

	AsyncHttpServer server = AsyncHttpServer.create(eventloop,
			request ->
					Promise.ofCallback(cb ->
							eventloop.post(() -> cb.set(
									HttpResponse.ok200()
											.withBody(encodeAscii(request.getUrl().getPathAndQuery()))))))
			.withListenPort(port);

	server.listen();

	Thread thread = new Thread(eventloop);
	thread.start();

	Socket socket = new Socket();

	socket.connect(new InetSocketAddress("localhost", port));
	write(socket, "GET /abc  HTTP/1.1\nHost: \tlocalhost\n\n");
	readAndAssert(socket.getInputStream(), "HTTP/1.1 200 OK\r\nConnection: keep-alive\r\nContent-Length: 4\r\n\r\n/abc");
	write(socket, "GET /abc  HTTP/1.0\nHost: \tlocalhost \t \nConnection: keep-alive\n\n");
	readAndAssert(socket.getInputStream(), "HTTP/1.1 200 OK\r\nConnection: keep-alive\r\nContent-Length: 4\r\n\r\n/abc");
	write(socket, "GET /abc  HTTP1.1\nHost: \tlocalhost \t \n\n");
	readAndAssert(socket.getInputStream(), "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 4\r\n\r\n/abc");
	assertEquals(0, toByteArray(socket.getInputStream()).length);
	socket.close();

	server.closeFuture().get();
	thread.join();
}
 
Example #22
Source File: StramClientUtils.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
public InetSocketAddress getRMHAAddress(String rmId)
{
  YarnConfiguration yarnConf = StramClientUtils.getYarnConfiguration(conf);
  yarnConf.set(ConfigUtils.RM_HA_ID, rmId);
  InetSocketAddress socketAddr = yarnConf.getSocketAddr(YarnConfiguration.RM_ADDRESS, YarnConfiguration.DEFAULT_RM_ADDRESS, YarnConfiguration.DEFAULT_RM_PORT);
  yarnConf.unset(ConfigUtils.RM_HA_ID);
  return socketAddr;
}
 
Example #23
Source File: HttpNegotiateServer.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates and starts an HTTP or proxy server that requires
 * Negotiate authentication.
 * @param scheme "Negotiate" or "Kerberos"
 * @param principal the krb5 service principal the server runs with
 * @return the server
 */
public static HttpServer httpd(String scheme, boolean proxy,
        String principal, String ktab) throws Exception {
    MyHttpHandler h = new MyHttpHandler();
    HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
    HttpContext hc = server.createContext("/", h);
    hc.setAuthenticator(new MyServerAuthenticator(
            proxy, scheme, principal, ktab));
    server.start();
    return server;
}
 
Example #24
Source File: HttpClientBuilderTest.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Test
public void httpClientWithStaticLoadBalancing() throws Exception {

    DefaultServiceDiscovererEvent<InetSocketAddress> sdEvent = new DefaultServiceDiscovererEvent<>(
            (InetSocketAddress) serverContext.listenAddress(), true);

    sendRequestAndValidate(Publisher.from(sdEvent));
}
 
Example #25
Source File: ChannelUtil.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public static String getRemoteIp(Channel channel) {
    InetSocketAddress inetSocketAddress = (InetSocketAddress) channel.remoteAddress();
    if (inetSocketAddress == null) {
        return "";
    }
    final InetAddress inetAddr = inetSocketAddress.getAddress();
    return inetAddr != null ? inetAddr.getHostAddress() : inetSocketAddress.getHostName();
}
 
Example #26
Source File: Sender.java    From dht-spider with MIT License 5 votes vote down vote up
/**
 * 回复find_node回复
 */
public  void findNodeReceive(String messageId,InetSocketAddress address, String nodeId, List<Node> nodeList,int num) {
    if(!channels.get(num).isWritable()){
        return;
    }
    FindNodeResponse findNodeResponse=new FindNodeResponse(messageId,nodeId,new String(Node.toBytes(nodeList), CharsetUtil.ISO_8859_1));
    channels.get(num).writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(bencode.encode(DHTUtil.beanToMap(findNodeResponse))), address));
}
 
Example #27
Source File: VertxRLPxServiceTest.java    From cava with Apache License 2.0 5 votes vote down vote up
@Test
void connectToOtherPeer(@VertxInstance Vertx vertx) throws Exception {
  SECP256K1.KeyPair ourPair = SECP256K1.KeyPair.random();
  SECP256K1.KeyPair peerPair = SECP256K1.KeyPair.random();
  VertxRLPxService service = new VertxRLPxService(
      vertx,
      LoggerProvider.nullProvider(),
      0,
      "localhost",
      10000,
      ourPair,
      new ArrayList<>(),
      "abc");
  service.start().join();

  VertxRLPxService peerService = new VertxRLPxService(
      vertx,
      LoggerProvider.nullProvider(),
      0,
      "localhost",
      10000,
      peerPair,
      new ArrayList<>(),
      "abc");
  peerService.start().join();

  try {
    service.connectTo(peerPair.publicKey(), new InetSocketAddress(peerService.actualPort()));
  } finally {
    service.stop();
    peerService.stop();
  }
}
 
Example #28
Source File: ClientFactory.java    From xio with Apache License 2.0 5 votes vote down vote up
protected Optional<Client> getHandlerClient(
    ChannelHandlerContext ctx, InetSocketAddress address) {
  return Optional.ofNullable(getClientMap(ctx).get(address))
      .flatMap(
          it -> {
            if (it.isReusable()) {
              return Optional.of(it);
            } else {
              getClientMap(ctx).remove(address);
              return Optional.empty();
            }
          });
}
 
Example #29
Source File: Portmap.java    From hadoop with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
  StringUtils.startupShutdownMessage(Portmap.class, args, LOG);

  final int port = RpcProgram.RPCB_PORT;
  Portmap pm = new Portmap();
  try {
    pm.start(DEFAULT_IDLE_TIME_MILLISECONDS,
        new InetSocketAddress(port), new InetSocketAddress(port));
  } catch (Throwable e) {
    LOG.fatal("Failed to start the server. Cause:", e);
    pm.shutdown();
    System.exit(-1);
  }
}
 
Example #30
Source File: ClientModule.java    From datakernel with Apache License 2.0 5 votes vote down vote up
@Provides
RpcClient rpcClient(Eventloop eventloop) {
	return RpcClient.create(eventloop)
			.withConnectTimeout(Duration.ofSeconds(1))
			.withSerializerBuilder(SerializerBuilder.create(Thread.currentThread().getContextClassLoader()))
			.withMessageTypes(PutRequest.class, PutResponse.class, GetRequest.class, GetResponse.class)
			.withStrategy(RpcStrategies.server(new InetSocketAddress("localhost", RPC_SERVER_PORT)));
}