Java Code Examples for io.netty.channel.socket.SocketChannel#remoteAddress()

The following examples show how to use io.netty.channel.socket.SocketChannel#remoteAddress() . 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: MysqlServerHandler.java    From antsdb with GNU Lesser General Public License v3.0 5 votes vote down vote up
public MysqlServerHandler(SaltedFish fish, SocketChannel ch) {
    this.fish = fish;
    this.channel=ch;
    this.out = new ChannelWriterNetty(ch);
    this.mysession = new MysqlSession(fish, this.out, ch.remoteAddress());
    this.packetEncoder = this.mysession.encoder;
}
 
Example 2
Source File: FrontendNettyChannelInitializer.java    From ambry with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
  // If channel handler implementations are not annotated with @Sharable, Netty creates a new instance of every class
  // in the pipeline for every connection.
  // i.e. if there are a 1000 active connections there will be a 1000 NettyMessageProcessor instances.
  ChannelPipeline pipeline = ch.pipeline();
  // connection stats handler to track connection related metrics
  pipeline.addLast("connectionStatsHandler", connectionStatsHandler);
  // if SSL is enabled, add an SslHandler before the HTTP codec
  if (sslFactory != null) {
    InetSocketAddress peerAddress = ch.remoteAddress();
    String peerHost = peerAddress.getHostName();
    int peerPort = peerAddress.getPort();
    SslHandler sslHandler = new SslHandler(sslFactory.createSSLEngine(peerHost, peerPort, SSLFactory.Mode.SERVER));
    pipeline.addLast("sslHandler", sslHandler);
  }
  pipeline
      // for http encoding/decoding.
      .addLast("codec",
          new HttpServerCodec(nettyConfig.nettyServerMaxInitialLineLength, nettyConfig.nettyServerMaxHeaderSize,
              nettyConfig.nettyServerMaxChunkSize))
      // for health check request handling
      .addLast("healthCheckHandler", new HealthCheckHandler(restServerState, nettyMetrics))
      // for public access logging
      .addLast("publicAccessLogHandler", new PublicAccessLogHandler(publicAccessLogger, nettyMetrics))
      // for detecting connections that have been idle too long - probably because of an error.
      .addLast("idleStateHandler", new IdleStateHandler(0, 0, nettyConfig.nettyServerIdleTimeSeconds))
      // for safe writing of chunks for responses
      .addLast("chunker", new ChunkedWriteHandler());
  if (addedChannelHandlers != null) {
    pipeline.addLast(addedChannelHandlers.toArray(new ChannelHandler[0]));
  }
  // custom processing class that interfaces with a RestRequestService.
  pipeline.addLast("processor",
      new NettyMessageProcessor(nettyMetrics, nettyConfig, performanceConfig, requestHandler));
}
 
Example 3
Source File: StorageServerNettyChannelInitializer.java    From ambry with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
  // To honor http2 window size, WriteBufferWaterMark.high() should be greater or equal to http2 window size.
  // Also see: https://github.com/netty/netty/issues/10193
  // https://stackoverflow.com/questions/25281124/netty-4-high-and-low-write-watermarks
  ch.config()
      .setSendBufferSize(http2ClientConfig.nettySendBufferSize)
      .setReceiveBufferSize(http2ClientConfig.nettyReceiveBufferSize)
      .setWriteBufferWaterMark(new WriteBufferWaterMark(http2ClientConfig.http2InitialWindowSize,
          2 * http2ClientConfig.http2InitialWindowSize));
  // If channel handler implementations are not annotated with @Sharable, Netty creates a new instance of every class
  // in the pipeline for every connection.
  // i.e. if there are a 1000 active connections there will be a 1000 NettyMessageProcessor instances.
  ChannelPipeline pipeline = ch.pipeline();
  // connection stats handler to track connection related metrics
  pipeline.addLast("ConnectionStatsHandler", connectionStatsHandler);
  InetSocketAddress peerAddress = ch.remoteAddress();
  String peerHost = peerAddress.getHostName();
  int peerPort = peerAddress.getPort();
  SslHandler sslHandler = new SslHandler(sslFactory.createSSLEngine(peerHost, peerPort, SSLFactory.Mode.SERVER));
  pipeline.addLast("SslHandler", sslHandler);
  pipeline.addLast("SecurityChecker", serverSecurityHandler);
  pipeline.addLast("Http2FrameCodec", Http2FrameCodecBuilder.forServer()
      .initialSettings(Http2Settings.defaultSettings()
          .maxFrameSize(http2ClientConfig.http2FrameMaxSize)
          .initialWindowSize(http2ClientConfig.http2InitialWindowSize))
      .frameLogger(new Http2FrameLogger(LogLevel.DEBUG, "server"))
      .build());
  pipeline.addLast("Http2MultiplexHandler", new Http2MultiplexHandler(http2ServerStreamHandler));
  pipeline.addLast("CloseOnExceptionHandler", closeOnExceptionHandler);
}
 
Example 4
Source File: BasicClient.java    From Bats with Apache License 2.0 4 votes vote down vote up
@Override
protected CC initRemoteConnection(SocketChannel channel){
  local=channel.localAddress();
  remote=channel.remoteAddress();
  return null;
}
 
Example 5
Source File: BasicServer.java    From Bats with Apache License 2.0 4 votes vote down vote up
@Override
protected SC initRemoteConnection(SocketChannel channel) {
  local = channel.localAddress();
  remote = channel.remoteAddress();
  return null;
}
 
Example 6
Source File: Service.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
public void asyncSendEthereumMessage(BcosRequest request, BcosResponseCallback callback) {
    BcosMessage bcosMessage = new BcosMessage();

    bcosMessage.setSeq(request.getMessageID());
    bcosMessage.setResult(0);
    bcosMessage.setType((short) 0x12);
    bcosMessage.setData(request.getContent().getBytes());
    // select node
    try {
        ChannelConnections channelConnections =
                allChannelConnections
                        .getAllChannelConnections()
                        .stream()
                        .filter(x -> x.getGroupId() == groupId)
                        .findFirst()
                        .get();

        if (channelConnections == null) {
            if (orgID != null) {
                logger.error("not found:{}", orgID);
                throw new TransactionException("not found orgID");
            } else {
                logger.error("not found:{}", agencyName);
                throw new TransactionException("not found agencyName");
            }
        }
        ChannelHandlerContext ctx =
                channelConnections.randomNetworkConnection(nodeToBlockNumberMap);

        ByteBuf out = ctx.alloc().buffer();
        bcosMessage.writeHeader(out);
        bcosMessage.writeExtra(out);

        seq2Callback.put(request.getMessageID(), callback);

        if (request.getTimeout() > 0) {
            final BcosResponseCallback callbackInner = callback;
            callback.setTimeout(
                    timeoutHandler.newTimeout(
                            new TimerTask() {
                                BcosResponseCallback _callback = callbackInner;

                                @Override
                                public void run(Timeout timeout) throws Exception {
                                    // handle timer
                                    _callback.onTimeout();
                                }
                            },
                            request.getTimeout(),
                            TimeUnit.MILLISECONDS));
        }

        ctx.writeAndFlush(out);
        SocketChannel socketChannel = (SocketChannel) ctx.channel();
        InetSocketAddress socketAddress = socketChannel.remoteAddress();
        logger.debug(
                "selected node {}:{} bcos request, seq:{}",
                socketAddress.getAddress().getHostAddress(),
                socketAddress.getPort(),
                bcosMessage.getSeq());

    } catch (Exception e) {
        logger.error(" error message:{}, error: {} ", e.getMessage(), e);

        BcosResponse response = new BcosResponse();
        response.setErrorCode(-1);
        response.setErrorMessage(
                e.getMessage()
                        + " requset send failed! please check the log file content for reasons.");
        response.setContent("");
        response.setMessageID(request.getMessageID());

        if (callback.getTimeout() != null) {
            callback.getTimeout().cancel();
        }
        callback.onResponse(response);
    }
}
 
Example 7
Source File: UserRPCServer.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
public UserClientConnectionImpl(SocketChannel channel) {
  super(channel, "user client", false);
  uuid = UUID.randomUUID();
  remote = channel.remoteAddress();
}