List of usage examples for io.netty.channel ChannelFuture channel
Channel channel();
From source file:com.mpush.client.gateway.connection.GatewayTCPConnectionFactory.java
License:Apache License
private void addConnection(String host, int port, boolean sync) { ChannelFuture future = client.connect(host, port); future.channel().attr(attrKey).set(getHostAndPort(host, port)); future.addListener(f -> {//from w w w . j a v a 2 s . co m if (!f.isSuccess()) { logger.error("create gateway connection ex, host={}, port={}", host, port, f.cause()); } }); if (sync) future.awaitUninterruptibly(); }
From source file:com.mpush.core.push.BroadcastPushTask.java
License:Apache License
@Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) {//?? Logs.PUSH.info("[Broadcast] push message to client success, userId={}, message={}", message.getUserId(), message);// w w w . ja v a 2 s . co m } else {//? Logs.PUSH.warn("[Broadcast] push message to client failure, userId={}, message={}, conn={}", message.getUserId(), message, future.channel()); } if (finishTasks.decrementAndGet() == 0) { report(); } }
From source file:com.mpush.core.push.SingleUserPushTask.java
License:Apache License
@Override public void operationComplete(ChannelFuture future) throws Exception { if (checkTimeout()) return;//from ww w . java 2s .c o m if (future.isSuccess()) {//?? if (message.isNeedAck()) {//?ACK, ?ACK addAckTask(messageId); } else { PushCenter.I.getPushListener().onSuccess(message, timeLine.successEnd().getTimePoints()); } Logs.PUSH.info("[SingleUserPush] push message to client success, timeLine={}, message={}", timeLine, message); } else {//? PushCenter.I.getPushListener().onFailure(message, timeLine.failureEnd().getTimePoints()); Logs.PUSH.error("[SingleUserPush] push message to client failure, message={}, conn={}", message, future.channel()); } }
From source file:com.mpush.netty.connection.NettyConnection.java
License:Apache License
@Override public ChannelFuture send(Packet packet, final ChannelFutureListener listener) { if (channel.isActive()) { ChannelFuture future = channel.writeAndFlush(packet.toFrame(channel)).addListener(this); if (listener != null) { future.addListener(listener); }//from w w w . ja v a2 s . com if (channel.isWritable()) { return future; } // //return channel.newPromise().setFailure(new RuntimeException("send data too busy")); if (!future.channel().eventLoop().inEventLoop()) { future.awaitUninterruptibly(100); } return future; } else { /*if (listener != null) { channel.newPromise() .addListener(listener) .setFailure(new RuntimeException("connection is disconnected")); }*/ return this.close(); } }
From source file:com.mpush.netty.server.NettyServer.java
License:Apache License
private void createServer(final Listener listener, EventLoopGroup boss, EventLoopGroup work, Class<? extends ServerChannel> clazz) { /***//from ww w. ja v a2 s. co m * NioEventLoopGroup ??I/O? * Netty????EventLoopGroup?????? * ?2NioEventLoopGroup * ???boss?? * ???worker??? * boss?worker * ???Channels??EventLoopGroup * ??? */ this.bossGroup = boss; this.workerGroup = work; try { /** * ServerBootstrap ?NIO?? * ??Channel */ ServerBootstrap b = new ServerBootstrap(); /** * groupjava.lang.IllegalStateException: group not set */ b.group(bossGroup, workerGroup); /*** * ServerSocketChannelNIOselector? * Channel?. */ b.channel(clazz); /*** * ?????Channel * ChannelInitializer? * ?Channel * ?NettyServerHandler??Channel * ChannelPipeline?? * ??????pipeline * ?????? */ b.childHandler(new ChannelInitializer<SocketChannel>() { // (4) @Override public void initChannel(SocketChannel ch) throws Exception { initPipeline(ch.pipeline()); } }); initOptions(b); /*** * ??? */ ChannelFuture f = b.bind(port).sync().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { Logs.Console.error("server start success on:{}", port); if (listener != null) listener.onSuccess(port); } else { Logs.Console.error("server start failure on:{}", port, future.cause()); if (listener != null) listener.onFailure(future.cause()); } } }); if (f.isSuccess()) { serverState.set(State.Started); /** * socket */ f.channel().closeFuture().sync(); } } catch (Exception e) { logger.error("server start exception", e); if (listener != null) listener.onFailure(e); throw new ServiceException("server start exception, port=" + port, e); } finally { /*** * */ stop(null); } }
From source file:com.mpush.test.client.ConnClientBoot.java
License:Apache License
public ChannelFuture connect(InetSocketAddress remote, InetSocketAddress local, ClientConfig clientConfig) { ChannelFuture future = local != null ? bootstrap.connect(remote, local) : bootstrap.connect(remote); if (future.channel() != null) future.channel().attr(CONFIG_KEY).set(clientConfig); future.addListener(f -> {//from ww w .j a v a2s . com if (f.isSuccess()) { future.channel().attr(CONFIG_KEY).set(clientConfig); LOGGER.info("start netty client success, remote={}, local={}", remote, local); } else { LOGGER.error("start netty client failure, remote={}, local={}", remote, local, f.cause()); } }); return future; }
From source file:com.my.netty.object.ObjectEchoClient.java
License:Apache License
public void run() throws Exception { Bootstrap b = new Bootstrap(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {// w ww . j a v a 2 s . co m b.group(workerGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ObjectEncoder()) .addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null))) .addLast(new ObjectEchoClientHandler(firstMessageSize)); } }); // Start the connection attempt. System.out.println("client prepare connect"); ChannelFuture f1 = b.connect(host, port).sync(); ChannelFuture f2 = b.connect(host, port).sync(); f1.channel().closeFuture().sync(); f2.channel().closeFuture().sync(); } finally { System.out.println("client do finally"); workerGroup.shutdownGracefully(); System.out.println("client closing"); } }
From source file:com.nanxiaoqiang.test.netty.protocol.demo1.server.NettyServer.java
License:Apache License
public void bind() throws Exception { // ??NIO// w w w. j av a 2 s. co m EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100) .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws IOException { ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024, 4, 4));// ? ch.pipeline().addLast(new NettyMessageEncoder());// ? ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50));// ?? ch.pipeline().addLast(new LoginAuthRespHandler());// ch.pipeline().addLast("HeartBeatHandler", new HeartBeatRespHandler());// } }); // ??? ChannelFuture cf = b.bind(NettyConstant.REMOTEIP, NettyConstant.PORT); cf.channel().closeFuture().sync(); System.out.println("Netty server start ok : " + (NettyConstant.REMOTEIP + " : " + NettyConstant.PORT)); }
From source file:com.navercorp.nbasearc.gcp.PhysicalConnection.java
License:Apache License
private void connectionComplete(ChannelFuture cf) { if (cf.cause() != null) { eventLoop.getEventLoopGroup().schedule(reconnectJob, reconnectInterval, TimeUnit.MILLISECONDS); return;//w ww.j a v a 2s . com } gw.increaseActive(); ch = cf.channel(); channelConnected = true; setState(CONNECTED); }
From source file:com.navercorp.pinpoint.plugin.netty.NettyIT.java
License:Apache License
@Test public void writeTest() throws Exception { final CountDownLatch awaitLatch = new CountDownLatch(1); Bootstrap bootstrap = client();/*w ww. j a v a 2s. co m*/ bootstrap.connect(webServer.getHostname(), webServer.getListeningPort()) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { Channel channel = future.channel(); channel.pipeline().addLast(new SimpleChannelInboundHandler() { @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { awaitLatch.countDown(); } }); HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"); future.channel().writeAndFlush(request); } } }); boolean await = awaitLatch.await(3000, TimeUnit.MILLISECONDS); Assert.assertTrue(await); PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance(); verifier.printCache(); verifier.verifyTrace(event("NETTY", Bootstrap.class.getMethod("connect", SocketAddress.class), annotation("netty.address", webServer.getHostAndPort()))); verifier.verifyTrace(event("NETTY", "io.netty.channel.DefaultChannelPromise.addListener(io.netty.util.concurrent.GenericFutureListener)")); verifier.verifyTrace(event("ASYNC", "Asynchronous Invocation")); verifier.verifyTrace( event("NETTY_INTERNAL", "io.netty.util.concurrent.DefaultPromise.notifyListenersNow()")); verifier.verifyTrace(event("NETTY_INTERNAL", "io.netty.util.concurrent.DefaultPromise.notifyListener0(io.netty.util.concurrent.Future, io.netty.util.concurrent.GenericFutureListener)")); verifier.verifyTrace( event("NETTY", "io.netty.channel.DefaultChannelPipeline.writeAndFlush(java.lang.Object)")); verifier.verifyTrace(event("NETTY_HTTP", "io.netty.handler.codec.http.HttpObjectEncoder.encode(io.netty.channel.ChannelHandlerContext, java.lang.Object, java.util.List)", annotation("http.url", "/"))); }