Java Code Examples for io.netty.channel.ChannelFuture

The following are top voted examples for showing how to use io.netty.channel.ChannelFuture. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: simulacron   File: ChannelUtils.java   Source Code and License 7 votes vote down vote up
/**
 * Convenience method to convert a {@link ChannelFuture} into a {@link CompletableFuture}
 *
 * @param future future to convert.
 * @return converted future.
 */
public static CompletableFuture<Void> completable(ChannelFuture future) {
  CompletableFuture<Void> cf = new CompletableFuture<>();
  future.addListener(
      (ChannelFutureListener)
          future1 -> {
            if (future1.isSuccess()) {
              cf.complete(null);
            } else {
              cf.completeExceptionally(future1.cause());
            }
          });
  return cf;
}
 
Example 2
Project: jsf-sdk   File: HttpJsonHandler.java   Source Code and License 7 votes vote down vote up
public static int writeBack(Channel channel, boolean isSuccess, String resultStr, boolean isKeepAlive) {
    ByteBuf content = Unpooled.copiedBuffer(resultStr, Constants.DEFAULT_CHARSET);
    HttpResponseStatus status;
    if (isSuccess) {
        status = HttpResponseStatus.OK;
    } else {
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
    }
    FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, status, content);
    //logger.info("result str:{}", resultStr);
    res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
    HttpHeaders.setContentLength(res, content.readableBytes());
    try {
        ChannelFuture f = channel.writeAndFlush(res);
        if (isKeepAlive) {
            HttpHeaders.setKeepAlive(res, true);
        } else {
            HttpHeaders.setKeepAlive(res, false);//set keepalive closed
            f.addListener(ChannelFutureListener.CLOSE);
        }
    } catch (Exception e2) {
        logger.warn("Failed to send HTTP response to remote, cause by:", e2);
    }

    return content.readableBytes();
}
 
Example 3
Project: AppCoins-ethereumj   File: PeerClient.java   Source Code and License 6 votes vote down vote up
/**
 *  Connects to the node and returns only upon connection close
 */
public void connect(String host, int port, String remoteId, boolean discoveryMode) {
    try {
        ChannelFuture f = connectAsync(host, port, remoteId, discoveryMode);

        f.sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();

        logger.debug("Connection is closed");

    } catch (Exception e) {
        if (discoveryMode) {
            logger.trace("Exception:", e);
        } else {
            if (e instanceof IOException) {
                logger.info("PeerClient: Can't connect to " + host + ":" + port + " (" + e.getMessage() + ")");
                logger.debug("PeerClient.connect(" + host + ":" + port + ") exception:", e);
            } else {
                logger.error("Exception:", e);
            }
        }
    }
}
 
Example 4
Project: simulacron   File: BoundNode.java   Source Code and License 6 votes vote down vote up
/**
 * Reopens the listening channel for this node. If the channel was already open, has no effect and
 * future completes immediately.
 *
 * @return future that completes when listening channel is reopened.
 */
private CompletableFuture<Void> rebind() {
  if (this.channel.get().isOpen()) {
    // already accepting...
    return CompletableFuture.completedFuture(null);
  }
  CompletableFuture<Void> future = new CompletableFuture<>();
  ChannelFuture bindFuture = bootstrap.bind(this.getAddress());
  bindFuture.addListener(
      (ChannelFutureListener)
          channelFuture -> {
            if (channelFuture.isSuccess()) {
              channelFuture.channel().attr(Server.HANDLER).set(this);
              logger.debug("Bound {} to {}", BoundNode.this, channelFuture.channel());
              future.complete(null);
              channel.set(channelFuture.channel());
            } else {
              // If failed, propagate it.
              future.completeExceptionally(
                  new BindNodeException(BoundNode.this, getAddress(), channelFuture.cause()));
            }
          });
  return future;
}
 
Example 5
Project: Backmemed   File: NetworkSystem.java   Source Code and License 6 votes vote down vote up
/**
 * Adds a channel that listens locally
 */
public SocketAddress addLocalEndpoint()
{
    ChannelFuture channelfuture;

    synchronized (this.endpoints)
    {
        channelfuture = ((ServerBootstrap)((ServerBootstrap)(new ServerBootstrap()).channel(LocalServerChannel.class)).childHandler(new ChannelInitializer<Channel>()
        {
            protected void initChannel(Channel p_initChannel_1_) throws Exception
            {
                NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.SERVERBOUND);
                networkmanager.setNetHandler(new NetHandlerHandshakeMemory(NetworkSystem.this.mcServer, networkmanager));
                NetworkSystem.this.networkManagers.add(networkmanager);
                p_initChannel_1_.pipeline().addLast((String)"packet_handler", (ChannelHandler)networkmanager);
            }
        }).group((EventLoopGroup)SERVER_NIO_EVENTLOOP.getValue()).localAddress(LocalAddress.ANY)).bind().syncUninterruptibly();
        this.endpoints.add(channelfuture);
    }

    return channelfuture.channel().localAddress();
}
 
Example 6
Project: BaseClient   File: NetworkSystem.java   Source Code and License 6 votes vote down vote up
/**
 * Adds a channel that listens locally
 */
public SocketAddress addLocalEndpoint()
{
    ChannelFuture channelfuture;

    synchronized (this.endpoints)
    {
        channelfuture = ((ServerBootstrap)((ServerBootstrap)(new ServerBootstrap()).channel(LocalServerChannel.class)).childHandler(new ChannelInitializer<Channel>()
        {
            protected void initChannel(Channel p_initChannel_1_) throws Exception
            {
                NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.SERVERBOUND);
                networkmanager.setNetHandler(new NetHandlerHandshakeMemory(NetworkSystem.this.mcServer, networkmanager));
                NetworkSystem.this.networkManagers.add(networkmanager);
                p_initChannel_1_.pipeline().addLast((String)"packet_handler", (ChannelHandler)networkmanager);
            }
        }).group((EventLoopGroup)eventLoops.getValue()).localAddress(LocalAddress.ANY)).bind().syncUninterruptibly();
        this.endpoints.add(channelfuture);
    }

    return channelfuture.channel().localAddress();
}
 
Example 7
Project: onedatashare   File: HTTPBuilder.java   Source Code and License 6 votes vote down vote up
/**
 * Establishes a new socket connection with connection test
 */
protected void setupWithTest() {
  ChannelFuture future = boot.connect(uri.host(), port);
  future.addListener(
      new GenericFutureListener<ChannelFuture>() {

        public void operationComplete(ChannelFuture f) {
          if (f.isSuccess()) {
            channel = (HTTPChannel) f.channel();
            testConnection();
            onTestBell.promise(onConnectBell);
          } else {
            onConnectBell.ring(f.cause());
          }
        }
      });
}
 
Example 8
Project: BaseClient   File: NetworkSystem.java   Source Code and License 6 votes vote down vote up
/**
 * Shuts down all open endpoints (with immediate effect?)
 */
public void terminateEndpoints()
{
    this.isAlive = false;

    for (ChannelFuture channelfuture : this.endpoints)
    {
        try
        {
            channelfuture.channel().close().sync();
        }
        catch (InterruptedException var4)
        {
            logger.error("Interrupted whilst closing channel");
        }
    }
}
 
Example 9
Project: CustomWorldGen   File: NetworkSystem.java   Source Code and License 6 votes vote down vote up
/**
 * Shuts down all open endpoints (with immediate effect?)
 */
public void terminateEndpoints()
{
    this.isAlive = false;

    for (ChannelFuture channelfuture : this.endpoints)
    {
        try
        {
            channelfuture.channel().close().sync();
        }
        catch (InterruptedException var4)
        {
            LOGGER.error("Interrupted whilst closing channel");
        }
    }
}
 
Example 10
Project: DecompiledMinecraft   File: NetworkSystem.java   Source Code and License 6 votes vote down vote up
/**
 * Shuts down all open endpoints (with immediate effect?)
 */
public void terminateEndpoints()
{
    this.isAlive = false;

    for (ChannelFuture channelfuture : this.endpoints)
    {
        try
        {
            channelfuture.channel().close().sync();
        }
        catch (InterruptedException var4)
        {
            logger.error("Interrupted whilst closing channel");
        }
    }
}
 
Example 11
Project: easysocket   File: NettyChannel.java   Source Code and License 6 votes vote down vote up
@Override
public ProtocolFuture write(byte[] data) {
    this.lastActive = System.currentTimeMillis();
    if (!isClosed()) {
        ChannelFuture future = channel.write(data);
        return new ProtocolFuture() {
            @Override
            public boolean isSuccess() {
                return future.isSuccess();
            }

            @Override
            public boolean isDone() {
                return future.isDone();
            }
        };
    } else {
        return ProtocolFuture.ERRORFUTURE;
    }
}
 
Example 12
Project: AlphaLibary   File: EchoServerHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;
    String sentData = in.toString(CharsetUtil.UTF_8);
    String returnee = sentData + "-::=::-" + "{}";

    RequestProcessor reprocessor = EchoServer.process(sentData);

    if (reprocessor != null)
        returnee = sentData + "-::=::-" + reprocessor.getProcessedData();

    ChannelFuture f = ctx.writeAndFlush(Unpooled.copiedBuffer(returnee, CharsetUtil.UTF_8)).sync();

    if (!f.isSuccess())
        try {
            throw f.cause();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
}
 
Example 13
Project: upgradeToy   File: SimpleClient.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {
    Bootstrap b = new Bootstrap();
    b.group(new NioEventLoopGroup())
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                }
            });
    b.connect("localhost", 8090).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                future.channel().write(Unpooled.buffer().writeBytes("123".getBytes()));
                future.channel().flush();
                future.channel().close();
            }
        }
    });
}
 
Example 14
Project: mqttserver   File: HttpJsonpTransport.java   Source Code and License 6 votes vote down vote up
private static void sendHttpResponse(ChannelHandlerContext ctx,
		HttpRequest req, FullHttpResponse res) {
	// Generate an error page if response getStatus code is not OK (200).
	if (res.getStatus().code() != 200) {
		ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(),
				CharsetUtil.UTF_8);
		res.content().writeBytes(buf);
		buf.release();
		setContentLength(res, res.content().readableBytes());
	}

	// Send the response and close the connection if necessary.
	ChannelFuture f = ctx.writeAndFlush(res);
	if (!isKeepAlive(req) || res.getStatus().code() != 200) {
		f.addListener(ChannelFutureListener.CLOSE);
	}
}
 
Example 15
Project: elasticsearch_my   File: Netty4HttpServerTransport.java   Source Code and License 6 votes vote down vote up
private TransportAddress bindAddress(final InetAddress hostAddress) {
    final AtomicReference<Exception> lastException = new AtomicReference<>();
    final AtomicReference<InetSocketAddress> boundSocket = new AtomicReference<>();
    boolean success = port.iterate(portNumber -> {
        try {
            synchronized (serverChannels) {
                ChannelFuture future = serverBootstrap.bind(new InetSocketAddress(hostAddress, portNumber)).sync();
                serverChannels.add(future.channel());
                boundSocket.set((InetSocketAddress) future.channel().localAddress());
            }
        } catch (Exception e) {
            lastException.set(e);
            return false;
        }
        return true;
    });
    if (!success) {
        throw new BindHttpException("Failed to bind to [" + port.getPortRangeString() + "]", lastException.get());
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Bound http to address {{}}", NetworkAddress.format(boundSocket.get()));
    }
    return new TransportAddress(boundSocket.get());
}
 
Example 16
Project: JPRE   File: TestClient.java   Source Code and License 6 votes vote down vote up
public void start() throws Exception {
	EventLoopGroup group = new NioEventLoopGroup();
	try {
		Bootstrap b = new Bootstrap();
		b.group(group)
				.channel(NioSocketChannel.class)
				.remoteAddress(new InetSocketAddress(this.host, this.port))
				.handler(new ChannelInitializer<SocketChannel>() {
					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						System.out.println("connected server...");
						ch.pipeline().addLast(new ByteArrayEncoder());
						ch.pipeline().addLast(new ByteArrayDecoder());
						ch.pipeline().addLast(new EchoClientHandler());
					}
				});

		ChannelFuture cf = b.connect().sync();

		cf.channel().closeFuture().sync();
	} finally {
		group.shutdownGracefully().sync();
	}
}
 
Example 17
Project: guereza   File: NettyServer.java   Source Code and License 6 votes vote down vote up
/**
 * Start the server
 *
 * @param port The port on which the server listen to
 */
public void run(final int port) {
    final EventLoopGroup bossGroup = new NioEventLoopGroup();
    final EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        final ServerBootstrap bootstrap = new ServerBootstrap()
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ServerInitializer())
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.TCP_NODELAY, true);

        final ChannelFuture f = bootstrap.bind(port).sync();
        LOGGER.info("NettyServer: running on port {}", port);

        f.channel().closeFuture().sync();
    } catch (final InterruptedException e) {
        LOGGER.error("NettyServer: an error occurred while running: {}", e.getMessage());
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example 18
Project: tasfe-framework   File: AsyncHttpServletHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object e) throws Exception {
    if (e instanceof ServletResponse) {
        logger.info("Handler async task...");
        HttpServletResponse response = (HttpServletResponse) e;
        Runnable task = ThreadLocalAsyncExecutor.pollTask(response);
        task.run();

        // write response...
        ChannelFuture future = ctx.channel().writeAndFlush(response);

        String keepAlive = response.getHeader(CONNECTION.toString());
        if (null != keepAlive && HttpHeaderValues.KEEP_ALIVE.toString().equalsIgnoreCase(keepAlive)) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    } else {
        ctx.fireChannelRead(e);
    }
}
 
Example 19
Project: heimdall-proxy   File: TcpServerToProxyServerHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void channelRead(final ChannelHandlerContext context, Object msg) {
    if(client.getInbound().isActive()) {
        client.getInbound().writeAndFlush(msg).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    context.channel().read();
                } else {
                    future.channel().close();
                }
            }
        });
    } else {
        client.getOutbound().close();
    }
}
 
Example 20
Project: NettyStudy   File: EchoClient.java   Source Code and License 6 votes vote down vote up
public void start() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
         .channel(NioSocketChannel.class)
         .remoteAddress(new InetSocketAddress(host, port))
         .handler(new ChannelInitializer<SocketChannel>() {
             @Override
             public void initChannel(SocketChannel ch) 
                 throws Exception {
                 ch.pipeline().addLast(
                         new EchoClientHandler());
             }
         });

        ChannelFuture f = bootstrap.connect().sync();

        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully().sync();
    }
}
 
Example 21
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: Broker2Client.java   Source Code and License 5 votes vote down vote up
/**
 * Broker主动回查Producer事务状态,Oneway
 */
public void checkProducerTransactionState(
    final Channel channel,
    final CheckTransactionStateRequestHeader requestHeader,
    final SelectMappedBufferResult selectMappedBufferResult) {
    RemotingCommand request =
        RemotingCommand.createRequestCommand(RequestCode.CHECK_TRANSACTION_STATE, requestHeader);
    request.markOnewayRPC();

    try {
        FileRegion fileRegion =
            new OneMessageTransfer(request.encodeHeader(selectMappedBufferResult.getSize()),
                selectMappedBufferResult);
        channel.writeAndFlush(fileRegion).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                selectMappedBufferResult.release();
                if (!future.isSuccess()) {
                    log.error("invokeProducer failed,", future.cause());
                }
            }
        });
    } catch (Throwable e) {
        log.error("invokeProducer exception", e);
        selectMappedBufferResult.release();
    }
}
 
Example 22
Project: simulacron   File: BoundNode.java   Source Code and License 5 votes vote down vote up
private static CompletableFuture<Void> closeChannelGroup(
    ChannelGroup channelGroup, CloseType closeType) {
  switch (closeType) {
    case DISCONNECT:
      return completable(channelGroup.disconnect());
    default:
      return CompletableFuture.allOf(
          channelGroup
              .stream()
              .map(
                  c -> {
                    CompletableFuture<Void> f;
                    Function<SocketChannel, ChannelFuture> shutdownMethod =
                        closeType == CloseType.SHUTDOWN_READ
                            ? SocketChannel::shutdownInput
                            : SocketChannel::shutdownOutput;
                    if (c instanceof SocketChannel) {
                      f = completable(shutdownMethod.apply((SocketChannel) c));
                    } else {
                      logger.warn(
                          "Got {} request for non-SocketChannel {}, disconnecting instead.",
                          closeType,
                          c);
                      f = completable(c.disconnect());
                    }
                    return f;
                  })
              .collect(Collectors.toList())
              .toArray(new CompletableFuture[] {}));
  }
}
 
Example 23
Project: dremio-oss   File: RpcBus.java   Source Code and License 5 votes vote down vote up
@Override
public void operationComplete(ChannelFuture future) throws Exception {
  final String msg = String.format("[%s]: Channel closed %s", rpcConfig.getName(), clientConnection.getName());

  final ChannelClosedException ex = future.cause() != null ? new ChannelClosedException(msg, future.cause()) : new ChannelClosedException(msg);
  logger.info(msg);
  clientConnection.channelClosed(ex);
}
 
Example 24
Project: heimdall-proxy   File: TcpProxyClient.java   Source Code and License 5 votes vote down vote up
@Override
public boolean start() {
    boolean result = false;
    do {
        TcpRouteDefinition route = definition.getRoute();

        if(null == route) {
            break;
        }
        if(route.getAddress() == null || route.getAddress().isEmpty()) {
            break;
        }
        if(route.getPort() == -1) {
            break;
        }

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(inbound.getClass());
            bootstrap.group(inbound.eventLoop());
            bootstrap.handler(new TcpProxyClientChannelInitializer(definition, this));
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.option(ChannelOption.AUTO_READ, false);

            ChannelFuture future = bootstrap.connect(route.getAddress(), route.getPort());
            //forwarder = future.sync().channel();
            outbound = future.channel();
            future.addListener(listener);
        } catch (Exception e) {
            log.error("Failed starting tcp proxy client.", e);
            outbound = null;
            break;
        }
        result = true;
    } while (false);
    return result;
}
 
Example 25
Project: monica   File: SocketServer.java   Source Code and License 5 votes vote down vote up
public void start() throws Exception {
	// Configure SSL.
	final SslContext sslCtx;
	if (SSL) {
		SelfSignedCertificate ssc = new SelfSignedCertificate();
		sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
	} else {
		sslCtx = null;
	}

	// Configure the server.
	EventLoopGroup bossGroup = new NioEventLoopGroup(1);
	EventLoopGroup workerGroup = new NioEventLoopGroup();
	try {
		ServerBootstrap b = new ServerBootstrap();
		b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100)
				.handler(new LoggingHandler(LogLevel.INFO)).childHandler(new FileServerHandlerInitializer());

		// Start the server.
		ChannelFuture f = b.bind(getHostAddress(), PORT).sync();
		// System.out.println("server is started "+f.isSuccess());
		setStarted(true);
		// Wait until the server socket is closed.
		f.channel().closeFuture().sync();
	} finally {
		// Shut down all event loops to terminate all threads.
		bossGroup.shutdownGracefully();
		workerGroup.shutdownGracefully();
	}

}
 
Example 26
Project: AgentX   File: XServer.java   Source Code and License 5 votes vote down vote up
public void start() {
    Configuration config = Configuration.INSTANCE;
    InternalLoggerFactory.setDefaultFactory(Slf4JLoggerFactory.INSTANCE);
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                                .addLast("logging", new LoggingHandler(LogLevel.DEBUG))
                                .addLast(new XConnectHandler());
                        if (config.getReadLimit() != 0 || config.getWriteLimit() != 0) {
                            socketChannel.pipeline().addLast(
                                    new GlobalTrafficShapingHandler(Executors.newScheduledThreadPool(1), config.getWriteLimit(), config.getReadLimit())
                            );
                        }
                    }
                });
        log.info("\tStartup {}-{}-server [{}]", Constants.APP_NAME, Constants.APP_VERSION, config.getProtocol());
        new Thread(() -> new UdpServer().start()).start();
        ChannelFuture future = bootstrap.bind(config.getHost(), config.getPort()).sync();
        future.addListener(future1 -> log.info("\tTCP listening at {}:{}...", config.getHost(), config.getPort()));
        future.channel().closeFuture().sync();
    } catch (Exception e) {
        log.error("\tSocket bind failure ({})", e.getMessage());
    } finally {
        log.info("\tShutting down and recycling...");
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        Configuration.shutdownRelays();
    }
    System.exit(0);
}
 
Example 27
Project: TakinRPC   File: SelectorUtil.java   Source Code and License 5 votes vote down vote up
public static void closeChannel(Channel channel) {
    final String addrRemote = RemotingHelper.parseChannelRemoteAddr(channel);
    channel.close().addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            logger.info("closeChannel: close the connection to remote address[{}] result: {}", addrRemote, future.isSuccess());
        }
    });
}
 
Example 28
Project: util4j   File: NettyServer.java   Source Code and License 5 votes vote down vote up
protected ChannelFuture doBooterBind(InetSocketAddress local,final ChannelHandler fixedHandler) {
	ChannelFuture cf;
	synchronized (booter) {
		final CountDownLatch latch=new CountDownLatch(1);
		LoggerHandler loggerHandler=null;//server接收处理链路的日志记录器
		LogLevel level=config.getLevel();
		if(level!=null)
		{
			loggerHandler=new LoggerHandler(level);
		}
		ChannelHandler childHandler=initLogHandlerAdapter(fixedHandler);
		booter.handler(loggerHandler).childHandler(childHandler);
		cf=booter.bind(local);
		cf.addListener(new ChannelFutureListener() {
			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				latch.countDown();
			}
		});
		try {
			latch.await(3,TimeUnit.SECONDS);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
	}
	return cf;
}
 
Example 29
Project: TakinRPC   File: RpcClient.java   Source Code and License 5 votes vote down vote up
@Override
public void operationComplete(ChannelFuture future) throws Exception {
    if (future.isDone() && future.isSuccess()) {
        set(new NettyRpcChannel(future.channel()));
    } else if (future.isDone() && future.cause() != null) {
        setException(future.cause());
    } else if (future.isDone() && future.isCancelled()) {
        cancel(false);
    }
}
 
Example 30
Project: PetiteRPC   File: NettyConnector.java   Source Code and License 5 votes vote down vote up
@Override
public Connection connect(Address address, Consumer<TransportChannel> successEvent) {
	Bootstrap bootstrap = bootstrap();
	final SocketAddress socketAddress = InetSocketAddress.createUnresolved(address.getHost(), address.getPort());	
	
	bootstrap.handler(new ChannelInitializer<Channel>() {

		@Override
		protected void initChannel(Channel ch) throws Exception {
			ch.pipeline()
			.addLast(new Encoder(serializer))
			.addLast(new Decoder(serializer))
			.addLast(new ConsumerHandler());
		}
		
	});
	
	ChannelFuture connectChannelFuture = bootstrap.connect(socketAddress);
	connectChannelFuture.addListener(new ChannelFutureListener() {
           
           @Override
           public void operationComplete(ChannelFuture future) throws Exception {
               if (future.isSuccess()) {
               		TransportChannel transportChannel = NettyChannel.getInstance(future.channel());
               		successEvent.accept(transportChannel);
               }
           }
       });
	return new NettyConnection(connectChannelFuture);
}
 
Example 31
Project: NettyStudy   File: NettyOioServer.java   Source Code and License 5 votes vote down vote up
public void server(int port) throws Exception {
    final ByteBuf buf = Unpooled.unreleasableBuffer(
            Unpooled.copiedBuffer("Hi!\r\n", Charset.forName("UTF-8")));
    EventLoopGroup group = new OioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();

        b.group(group)
         .channel(OioServerSocketChannel.class)
         .localAddress(new InetSocketAddress(port))
         .childHandler(new ChannelInitializer<SocketChannel>() {
             @Override
             public void initChannel(SocketChannel ch) 
                 throws Exception {
                 ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                     @Override
                     public void channelActive(ChannelHandlerContext ctx) throws Exception {
                         ctx.writeAndFlush(buf.duplicate()).addListener(ChannelFutureListener.CLOSE);
                     }
                 });
             }
         });
        ChannelFuture f = b.bind().sync();
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully().sync();
    }
}
 
Example 32
Project: sbrw-freeroam-srv   File: NettyUdpServer.java   Source Code and License 5 votes vote down vote up
public ChannelFuture start() throws InterruptedException {
	workerGroup = new NioEventLoopGroup();

	Bootstrap bootstrap = new Bootstrap();
	bootstrap.group(workerGroup).channel(NioDatagramChannel.class).handler(new ServerChannelInitializer());

	ChannelFuture channelFuture = bootstrap.bind(new InetSocketAddress(port)).syncUninterruptibly();
	channel = channelFuture.channel();

	return channelFuture;
}
 
Example 33
Project: elephant   File: RemotingUtil.java   Source Code and License 5 votes vote down vote up
public static void closeChannel(Channel channel) {
    final String addrRemote = RemotingHelper.parseChannelRemoteAddr(channel);
    channel.close().addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            log.info("closeChannel: close the connection to remote address[{}] result: {}", addrRemote,
                future.isSuccess());
        }
    });
}
 
Example 34
Project: spark_deep   File: TransportClient.java   Source Code and License 5 votes vote down vote up
/**
 * Request to stream the data with the given stream ID from the remote end.
 *
 * @param streamId The stream to fetch.
 * @param callback Object to call with the stream data.
 */
public void stream(final String streamId, final StreamCallback callback) {
  final long startTime = System.currentTimeMillis();
  if (logger.isDebugEnabled()) {
    logger.debug("Sending stream request for {} to {}", streamId, getRemoteAddress(channel));
  }

  // Need to synchronize here so that the callback is added to the queue and the RPC is
  // written to the socket atomically, so that callbacks are called in the right order
  // when responses arrive.
  synchronized (this) {
    handler.addStreamCallback(callback);
    channel.writeAndFlush(new StreamRequest(streamId)).addListener(
      new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
          if (future.isSuccess()) {
            long timeTaken = System.currentTimeMillis() - startTime;
            if (logger.isTraceEnabled()) {
              logger.trace("Sending request for {} to {} took {} ms", streamId,
                getRemoteAddress(channel), timeTaken);
            }
          } else {
            String errorMsg = String.format("Failed to send request for %s to %s: %s", streamId,
              getRemoteAddress(channel), future.cause());
            logger.error(errorMsg, future.cause());
            channel.close();
            try {
              callback.onFailure(streamId, new IOException(errorMsg, future.cause()));
            } catch (Exception e) {
              logger.error("Uncaught exception in RPC response callback handler!", e);
            }
          }
        }
      });
  }
}
 
Example 35
Project: candlelight   File: NetworkEngine.java   Source Code and License 5 votes vote down vote up
public void closeEndpoints()
{
	for(ChannelFuture ch : this.endpoints)
	{
		try
		{
			ch.channel().close().sync();
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}
	}
}
 
Example 36
Project: push   File: MgsServer.java   Source Code and License 5 votes vote down vote up
public void run() {
	ServerBootstrap b = new ServerBootstrap();// 引导辅助程序

	bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);
	workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);
	try {
		b.group(bossGroup, workerGroup);
		b.channel(NioServerSocketChannel.class);// 设置nio类型的channel
		b.childHandler(new ChannelInitializer<SocketChannel>() {// 有连接到达时会创建一个channel
			protected void initChannel(SocketChannel ch) throws Exception {
				logger.debug("客户端:{} 初始化", ch.remoteAddress());
				// pipeline管理channel中的Handler,在channel队列中添加一个handler来处理业务
				ch.pipeline().addLast("frameDecoder",
						new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
				ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4));
				ch.pipeline().addLast("decoder", msgPackDecode);
				ch.pipeline().addLast("encoder", msgPackEncode);
				ch.pipeline().addLast(serverHandler);
			}
		});
		b.option(ChannelOption.SO_BACKLOG, 128);
		b.childOption(ChannelOption.SO_KEEPALIVE, true);
		logger.info("server start : {}", port);
		ChannelFuture f = b.bind(port).sync();// 配置完成,开始绑定server,通过调用sync同步方法阻塞直到绑定成功
		channel = f.channel();
		f.channel().closeFuture().sync();// 应用程序会一直等待,直到channel关闭
	} catch (Exception e) {
		e.printStackTrace();
	}

}
 
Example 37
Project: nitmproxy   File: SocksProxyHandler.java   Source Code and License 5 votes vote down vote up
private void onSocksSuccess(ChannelHandlerContext ctx, Socks4CommandRequest request) {
    Address serverAddr = new Address(request.dstAddr(), request.dstPort());
    createServerChannel(ctx, serverAddr).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                ConnectionInfo newConnectionInfo = new ConnectionInfo(
                        connectionInfo.getClientAddr(), serverAddr);
                ctx.writeAndFlush(new DefaultSocks4CommandResponse(
                        Socks4CommandStatus.SUCCESS,
                        request.dstAddr(),
                        request.dstPort()));

                onServerConnected(ctx, newConnectionInfo, future.channel());
            } else {
                ctx.channel().writeAndFlush(new DefaultSocks4CommandResponse(
                        Socks4CommandStatus.REJECTED_OR_FAILED,
                        request.dstAddr(),
                        request.dstPort()));
                ctx.close();
            }
        }
    });
}
 
Example 38
Project: netty_op   File: ErrorTimeClient.java   Source Code and License 5 votes vote down vote up
/**
 *@description 连接服务器
 *@time 创建时间:2017年7月21日下午4:15:50
 *@param host
 *@param port
 *@throws InterruptedException
 *@author dzn
 */
public void connect(String host, int port) throws InterruptedException{
    EventLoopGroup group = new NioEventLoopGroup();
    try{
        
        //netty客户端
        Bootstrap boot = new Bootstrap();
        boot.group(group)
        .channel(NioSocketChannel.class)
        .option(ChannelOption.TCP_NODELAY, true)
        .handler(new ChannelInitializer<SocketChannel>() {
            
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                //对输入数据进行业务逻辑处理
                ch.pipeline().addLast(new ErrorTimeClientHandler());
            }
            
        });
        
        //使用netty客户端连接netty服务器
        ChannelFuture future = boot.connect(host, port).sync();
        
        //等待客户端Channel关闭
        future.channel().closeFuture().sync();
        
    }finally{
        group.shutdownGracefully();
    }
}
 
Example 39
Project: elasticsearch_my   File: Netty4OpenChannelsHandler.java   Source Code and License 5 votes vote down vote up
@Override
public void operationComplete(ChannelFuture future) throws Exception {
    boolean removed = openChannels.remove(future.channel());
    if (removed) {
        openChannelsMetric.dec();
    }
    if (logger.isTraceEnabled()) {
        logger.trace("channel closed: {}", future.channel());
    }
}
 
Example 40
Project: waterrower-core   File: RxtxCommunicationService.java   Source Code and License 5 votes vote down vote up
/**
 * Opens the connection to the given serial port.
 *
 * @param address The serial port, must not be null.
 * @throws IOException if opening of the channel fails.
 */
public void open(RxtxDeviceAddress address) throws IOException {
    requireNonNull(address);

    lock.lock();

    try {

        checkIfChannelIsClose();

        Log.debug(SERIAL, "Opening channel at serial port '" + address.value() + "'.");

        ChannelFuture future = bootstrap.connect(address).syncUninterruptibly();
        if (!future.isSuccess()) {
            fireOnError();
            throw new IOException("Serial channel couldn't be opened!");
        }

        Log.debug(SERIAL, "Serial channel was successfully opened.");

        currentChannel = future.channel();

    } catch (Exception e) {
        throw new IOException("Can not connect to '"+address.value()+"'!", e);
    } finally {
        lock.unlock();
    }
}
 
Example 41
Project: hekate   File: NettyClient.java   Source Code and License 5 votes vote down vote up
@Override
public void operationComplete(ChannelFuture future) throws Exception {
    connectComplete = true;

    if (future.isSuccess()) {
        if (future.channel().isOpen()) {
            if (trace) {
                log.trace("Channel connect future completed successfully [to={}]", id);
            }
        } else {
            // Channel was disconnect()'ed while we were connecting.
            becomeDisconnected();
        }
    } else if (firstError == null) {
        if (trace) {
            log.trace("Notifying on connect future failure [to={}]", id, future.cause());
        }

        firstError = NettyErrorUtils.unwrap(future.cause());

        ChannelPipeline pipeline = future.channel().pipeline();

        if (pipeline.names().contains(NettyClientStateHandler.class.getName())) {
            pipeline.fireExceptionCaught(firstError);
        } else {
            becomeDisconnected();
        }
    }
}
 
Example 42
Project: rmq4note   File: PullMessageProcessor.java   Source Code and License 5 votes vote down vote up
public void executeRequestWhenWakeup(final Channel channel, final RemotingCommand request) throws RemotingCommandException {
    Runnable run = new Runnable() {
        @Override
        public void run() {
            try {
                final RemotingCommand response = PullMessageProcessor.this.processRequest(channel, request, false);

                if (response != null) {
                    response.setOpaque(request.getOpaque());
                    response.markResponseType();
                    try {
                        channel.writeAndFlush(response).addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture future) throws Exception {
                                if (!future.isSuccess()) {
                                    LOG.error("ProcessRequestWrapper response to {} failed", future.channel().remoteAddress(), future.cause());
                                    LOG.error(request.toString());
                                    LOG.error(response.toString());
                                }
                            }
                        });
                    } catch (Throwable e) {
                        LOG.error("ProcessRequestWrapper process request over, but response failed", e);
                        LOG.error(request.toString());
                        LOG.error(response.toString());
                    }
                }
            } catch (RemotingCommandException e1) {
                LOG.error("ExecuteRequestWhenWakeup run", e1);
            }
        }
    };
    this.brokerController.getPullMessageExecutor().submit(new RequestTask(run, channel, request));
}
 
Example 43
Project: ditb   File: AsyncRpcChannel.java   Source Code and License 5 votes vote down vote up
/**
 * Start HBase connection
 *
 * @param ch channel to start connection on
 */
private void startHBaseConnection(Channel ch) {
  ch.pipeline()
      .addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
  ch.pipeline().addLast(new AsyncServerResponseHandler(this));
  try {
    writeChannelHeader(ch).addListener(new GenericFutureListener<ChannelFuture>() {
      @Override
      public void operationComplete(ChannelFuture future) throws Exception {
        if (!future.isSuccess()) {
          close(future.cause());
          return;
        }
        List<AsyncCall> callsToWrite;
        synchronized (pendingCalls) {
          connected = true;
          callsToWrite = new ArrayList<AsyncCall>(pendingCalls.values());
        }
        for (AsyncCall call : callsToWrite) {
          writeRequest(call);
        }
      }
    });
  } catch (IOException e) {
    close(e);
  }
}
 
Example 44
Project: Cobweb   File: Client.java   Source Code and License 5 votes vote down vote up
private void shortConnection(){
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(channelInitializer);
        ChannelFuture future = b.connect(host, port).sync();
        future.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example 45
Project: ConfigCenter   File: NettyRemotingAbstract.java   Source Code and License 5 votes vote down vote up
/**
 * 发送消息,不接收响应
 * @param channel
 * @param request
 * @param timeoutMillis
 * @throws InterruptedException
 * @throws RemotingTooMuchRequestException
 * @throws RemotingTimeoutException
 * @throws RemotingSendRequestException
 */
public void invokeOnewayImpl(final Channel channel, final RemotingCommand request, final long timeoutMillis)
        throws InterruptedException, RemotingTooMuchRequestException, RemotingTimeoutException, RemotingSendRequestException {
    request.markOnewayRPC();
    boolean acquired = this.semaphoreOneway.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS);
    if (acquired) {
        final SemaphoreReleaseOnlyOnce once = new SemaphoreReleaseOnlyOnce(this.semaphoreOneway);
        try {
            channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture f) throws Exception {
                    once.release();
                    if (!f.isSuccess()) {
                        plog.warn("send a request command to channel <" + channel.remoteAddress() + "> failed.");
                    }
                }
            });
        } catch (Exception e) {
            once.release();
            plog.warn("write send a request command to channel <" + channel.remoteAddress() + "> failed.");
            throw new RemotingSendRequestException(RemotingHelper.parseChannelRemoteAddr(channel), e);
        }
    } else {
        if (timeoutMillis <= 0) {
            throw new RemotingTooMuchRequestException("invokeOnewayImpl invoke too fast");
        } else {
            String info = String.format(
                    "invokeOnewayImpl tryAcquire semaphore timeout, %dms, waiting thread nums: %d semaphoreAsyncValue: %d", //
                    timeoutMillis, //
                    this.semaphoreOneway.getQueueLength(), //
                    this.semaphoreOneway.availablePermits()//
            );
            plog.warn(info);
            throw new RemotingTimeoutException(info);
        }
    }
}
 
Example 46
Project: drift   File: ThriftClientHandler.java   Source Code and License 5 votes vote down vote up
private void sendMessage(ChannelHandlerContext context, ThriftRequest thriftRequest, ChannelPromise promise)
        throws Exception
{
    // todo ONEWAY_SEQUENCE_ID is a header protocol thing... make sure this works with framed and unframed
    int sequenceId = thriftRequest.isOneway() ? ONEWAY_SEQUENCE_ID : this.sequenceId.incrementAndGet();
    RequestHandler requestHandler = new RequestHandler(thriftRequest, sequenceId);

    // register timeout
    requestHandler.registerRequestTimeout(context.executor());

    // write request
    ByteBuf requestBuffer = requestHandler.encodeRequest(context.alloc());

    // register request if we are expecting a response
    if (!thriftRequest.isOneway()) {
        if (pendingRequests.putIfAbsent(sequenceId, requestHandler) != null) {
            requestHandler.onChannelError(new TTransportException("Another request with the same sequenceId is already in progress"));
        }
    }

    try {
        ChannelFuture sendFuture = context.write(requestBuffer, promise);
        sendFuture.addListener(future -> messageSent(context, sendFuture, requestHandler));
    }
    catch (Throwable t) {
        onError(context, t);
    }
}
 
Example 47
Project: drift   File: ConnectionFactory.java   Source Code and License 5 votes vote down vote up
private static void notifyConnect(ChannelFuture future, Promise<Channel> promise)
{
    if (future.isSuccess()) {
        Channel channel = future.channel();
        if (!promise.trySuccess(channel)) {
            // Promise was completed in the meantime (likely cancelled), just release the channel again
            channel.close();
        }
    }
    else {
        promise.tryFailure(future.cause());
    }
}
 
Example 48
Project: L2J-Global   File: NetworkManager.java   Source Code and License 4 votes vote down vote up
public ChannelFuture getChannelFuture()
{
	return _channelFuture;
}
 
Example 49
Project: DecompiledMinecraft   File: NetHandlerLoginServer.java   Source Code and License 4 votes vote down vote up
public void tryAcceptPlayer()
{
    if (!this.loginGameProfile.isComplete())
    {
        this.loginGameProfile = this.getOfflineProfile(this.loginGameProfile);
    }

    String s = this.server.getConfigurationManager().allowUserToConnect(this.networkManager.getRemoteAddress(), this.loginGameProfile);

    if (s != null)
    {
        this.closeConnection(s);
    }
    else
    {
        this.currentLoginState = NetHandlerLoginServer.LoginState.ACCEPTED;

        if (this.server.getNetworkCompressionTreshold() >= 0 && !this.networkManager.isLocalChannel())
        {
            this.networkManager.sendPacket(new S03PacketEnableCompression(this.server.getNetworkCompressionTreshold()), new ChannelFutureListener()
            {
                public void operationComplete(ChannelFuture p_operationComplete_1_) throws Exception
                {
                    NetHandlerLoginServer.this.networkManager.setCompressionTreshold(NetHandlerLoginServer.this.server.getNetworkCompressionTreshold());
                }
            }, new GenericFutureListener[0]);
        }

        this.networkManager.sendPacket(new S02PacketLoginSuccess(this.loginGameProfile));
        EntityPlayerMP entityplayermp = this.server.getConfigurationManager().getPlayerByUUID(this.loginGameProfile.getId());

        if (entityplayermp != null)
        {
            this.currentLoginState = NetHandlerLoginServer.LoginState.DELAY_ACCEPT;
            this.field_181025_l = this.server.getConfigurationManager().createPlayerForUser(this.loginGameProfile);
        }
        else
        {
            this.server.getConfigurationManager().initializeConnectionToPlayer(this.networkManager, this.server.getConfigurationManager().createPlayerForUser(this.loginGameProfile));
        }
    }
}
 
Example 50
Project: libcwfincore   File: GdaxTransactionLoader.java   Source Code and License 4 votes vote down vote up
void requestPage(ChannelFuture channelFuture, String uri) throws GeneralSecurityException {
    session.sendRequest(channelFuture, new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri));
}
 
Example 51
Project: simulacron   File: MockClient.java   Source Code and License 4 votes vote down vote up
ChannelFuture write(Frame frame) {
  return this.channel.writeAndFlush(frame);
}
 
Example 52
Project: BaseClient   File: NetHandlerLoginServer.java   Source Code and License 4 votes vote down vote up
public void tryAcceptPlayer()
{
    if (!this.loginGameProfile.isComplete())
    {
        this.loginGameProfile = this.getOfflineProfile(this.loginGameProfile);
    }

    String s = this.server.getConfigurationManager().allowUserToConnect(this.networkManager.getRemoteAddress(), this.loginGameProfile);

    if (s != null)
    {
        this.closeConnection(s);
    }
    else
    {
        this.currentLoginState = NetHandlerLoginServer.LoginState.ACCEPTED;

        if (this.server.getNetworkCompressionTreshold() >= 0 && !this.networkManager.isLocalChannel())
        {
            this.networkManager.sendPacket(new S03PacketEnableCompression(this.server.getNetworkCompressionTreshold()), new ChannelFutureListener()
            {
                public void operationComplete(ChannelFuture p_operationComplete_1_) throws Exception
                {
                    NetHandlerLoginServer.this.networkManager.setCompressionTreshold(NetHandlerLoginServer.this.server.getNetworkCompressionTreshold());
                }
            }, new GenericFutureListener[0]);
        }

        this.networkManager.sendPacket(new S02PacketLoginSuccess(this.loginGameProfile));
        EntityPlayerMP entityplayermp = this.server.getConfigurationManager().getPlayerByUUID(this.loginGameProfile.getId());

        if (entityplayermp != null)
        {
            this.currentLoginState = NetHandlerLoginServer.LoginState.DELAY_ACCEPT;
            this.field_181025_l = this.server.getConfigurationManager().createPlayerForUser(this.loginGameProfile);
        }
        else
        {
            this.server.getConfigurationManager().initializeConnectionToPlayer(this.networkManager, this.server.getConfigurationManager().createPlayerForUser(this.loginGameProfile));
        }
    }
}
 
Example 53
Project: reading-and-annotate-rocketmq-3.4.6   File: QueryMessageProcessor.java   Source Code and License 4 votes vote down vote up
public RemotingCommand viewMessageById(ChannelHandlerContext ctx, RemotingCommand request)
        throws RemotingCommandException {
    final RemotingCommand response = RemotingCommand.createResponseCommand(null);
    final ViewMessageRequestHeader requestHeader =
            (ViewMessageRequestHeader) request.decodeCommandCustomHeader(ViewMessageRequestHeader.class);

    response.setOpaque(request.getOpaque());

    final SelectMapedBufferResult selectMapedBufferResult =
            this.brokerController.getMessageStore().selectOneMessageByOffset(requestHeader.getOffset());
    if (selectMapedBufferResult != null) {
        response.setCode(ResponseCode.SUCCESS);
        response.setRemark(null);

        try {
            FileRegion fileRegion =
                    new OneMessageTransfer(response.encodeHeader(selectMapedBufferResult.getSize()),
                        selectMapedBufferResult);
            ctx.channel().writeAndFlush(fileRegion).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    selectMapedBufferResult.release();
                    if (!future.isSuccess()) {
                        log.error("transfer one message by pagecache failed, ", future.cause());
                    }
                }
            });
        }
        catch (Throwable e) {
            log.error("", e);
            selectMapedBufferResult.release();
        }

        return null;
    }
    else {
        response.setCode(ResponseCode.SYSTEM_ERROR);
        response.setRemark("can not find message by the offset, " + requestHeader.getOffset());
    }

    return response;
}
 
Example 54
Project: QDrill   File: ControlServer.java   Source Code and License 4 votes vote down vote up
@Override
protected GenericFutureListener<ChannelFuture> getCloseHandler(SocketChannel ch, ControlConnection connection) {
  this.proxyCloseHandler = new ProxyCloseHandler(super.getCloseHandler(ch, connection));
  return proxyCloseHandler;
}
 
Example 55
Project: reading-and-annotate-rocketmq-3.4.6   File: NettyRemotingAbstract.java   Source Code and License 4 votes vote down vote up
public void invokeOnewayImpl(final Channel channel, final RemotingCommand request,
        final long timeoutMillis) throws InterruptedException, RemotingTooMuchRequestException,
        RemotingTimeoutException, RemotingSendRequestException {
    request.markOnewayRPC();
    boolean acquired = this.semaphoreOneway.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS);
    if (acquired) {
        final SemaphoreReleaseOnlyOnce once = new SemaphoreReleaseOnlyOnce(this.semaphoreOneway);
        try {
            channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture f) throws Exception {
                    once.release();
                    if (!f.isSuccess()) {
                        plog.warn("send a request command to channel <" + channel.remoteAddress()
                                + "> failed.");
                        plog.warn(request.toString());
                    }
                }
            });
        }
        catch (Exception e) {
            once.release();
            plog.warn("write send a request command to channel <" + channel.remoteAddress() + "> failed.");
            throw new RemotingSendRequestException(RemotingHelper.parseChannelRemoteAddr(channel), e);
        }
    }
    else {
        if (timeoutMillis <= 0) {
            throw new RemotingTooMuchRequestException("invokeOnewayImpl invoke too fast");
        }
        else {
            String info =
                    String
                        .format(
                            "invokeOnewayImpl tryAcquire semaphore timeout, %dms, waiting thread nums: %d semaphoreAsyncValue: %d", //
                            timeoutMillis,//
                            this.semaphoreAsync.getQueueLength(),//
                            this.semaphoreAsync.availablePermits()//
                        );
            plog.warn(info);
            plog.warn(request.toString());
            throw new RemotingTimeoutException(info);
        }
    }
}
 
Example 56
Project: TakinRPC   File: RemotingAbstract.java   Source Code and License 4 votes vote down vote up
/**
 * 发起同步调用
 * 其实后面也是异步的
 * 这个同步是指:可以携带结果返回
 * @param address
 * @param message
 * @param timeout
 * @return
 * @throws Exception
 */
@SuppressWarnings("rawtypes")
protected RemotingProtocol invokeSyncImpl(final Channel channel, final RemotingProtocol message, int timeout) throws Exception, RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException {
    final Stopwatch watch = Stopwatch.createStarted();
    try {
        final ResponseFuture responseFuture = new ResponseFuture(message.getOpaque(), timeout);
        //            logger.info("currentthread:" + Thread.currentThread().getName());
        logger.debug(String.format("create respnse future use:%s", watch.toString()));
        responseTable.put(message.getOpaque(), responseFuture);
        //            logger.debug(String.format("put future use:%s", watch.toString()));
        channel.writeAndFlush(message).addListener(new ChannelFutureListener() {
            //什么时候会触发这一个接口呢
            @Override
            public void operationComplete(ChannelFuture f) throws Exception {
                //此步代表发送操作成功   设置的sendrequest值是为了区分发送失败还是服务端处理失败的

                if (f.isSuccess()) {
                    responseFuture.setSendRequestOK(true);
                    //                        logger.debug(String.format("operationcomplete use:%s", watch.toString()));
                    return;
                } else {
                    responseFuture.setSendRequestOK(false);
                }
                //无结果 返回原因
                responseTable.remove(message.getOpaque());
                responseFuture.setCause(f.cause());
                responseFuture.putResponse(null);
                //                    logger.debug(String.format("operation no use:%s", watch.toString()));
            }
        });
        if (logger.isDebugEnabled())
            logger.debug(String.format("finish listener use:%s", watch.toString()));
        RemotingProtocol result = responseFuture.waitResponse();
        if (logger.isDebugEnabled())
            logger.debug(String.format("wait response use:%s", watch.toString()));
        if (null == result) {
            if (responseFuture.isSendRequestOK()) {
                throw new Exception("request timeout ");
            } else {
                throw new Exception("request error");
            }
        }
        if (logger.isDebugEnabled())
            logger.debug(String.format("invoke sync,use:%s", watch.toString()));
        return result;
    } catch (Exception e) {
        throw e;
    }
}
 
Example 57
Project: iothub   File: TcpChannelEntity.java   Source Code and License 4 votes vote down vote up
public void operationComplete(ChannelFuture future) {
	if (!future.isSuccess()) {
		future.channel().close();
	}
}
 
Example 58
Project: util4j   File: ConnectionBuilder.java   Source Code and License 4 votes vote down vote up
public static void main(String[] args) {
	ConnectionBuilder cb=new ConnectionBuilder();
	ChannelFuture cf=cb.connect(new InetSocketAddress("127.0.0.1", 4000));
	System.out.println(cf.channel());
}
 
Example 59
Project: qonduit   File: CaptureChannelHandlerContext.java   Source Code and License 4 votes vote down vote up
@Override
public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {
    return promise;
}
 
Example 60
Project: Stork   File: HTTPTestHandler.java   Source Code and License 4 votes vote down vote up
private void endTest(ChannelHandlerContext ctx) {
  final HTTPChannel ch = (HTTPChannel) ctx.channel();

  if (builder.isKeepAlive && (code == ActionCode.OK)) {
    builder.onTestBell.ring();
  } else {
    ch.disconnect();
    ch.close().addListener(new GenericFutureListener<ChannelFuture> () {

      public void operationComplete(ChannelFuture future) {

        switch(code.ordinal()) {
          case 3:
            if (ch.testMethod.equals(HttpMethod.HEAD)) {
              ch.testMethod = HttpMethod.GET;
            } else {
              System.err.println("Error: Bad request on " + 
                  builder.getHost() +
                  ". The session will be closed.");
              builder.close();
              ch.clear();
              ch.close();
              break;
            }
          case 1:
            builder.setupWithTest();
          case 2:
            break;
          case 0: 
            ch.onInactiveBell.ring();
            builder.onTestBell.promise(builder.onConnectBell);
            builder.onTestBell.ring();
            break;
          default:
            System.err.println(
                "Error: Unimplemented response code on " +
                builder.getHost() + ". The session will be closed.");
            builder.close();
            ch.close();
            break;
        }
      }
    });
  }
}