List of usage examples for io.netty.channel ChannelFutureListener ChannelFutureListener
ChannelFutureListener
From source file:com.gxkj.demo.netty.proxy.HexDumpProxyFrontendHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { final Channel inboundChannel = ctx.channel(); // Start the connection attempt. Bootstrap b = new Bootstrap(); b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass()) .handler(new HexDumpProxyBackendHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false); ChannelFuture f = b.connect(remoteHost, remotePort); outboundChannel = f.channel();/*from w w w . j a va2s . c o m*/ f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // connection complete start to read first data inboundChannel.read(); } else { // Close the connection if the connection attempt has failed. inboundChannel.close(); } } }); }
From source file:com.gxkj.demo.netty.proxy.HexDumpProxyFrontendHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception { if (outboundChannel.isActive()) { outboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() { @Override/* www .jav a 2 s. c o m*/ public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // was able to flush out data, start to read the next chunk ctx.channel().read(); } else { future.channel().close(); } } }); } }
From source file:com.gxkj.demo.netty.socksproxy.SocksServerConnectHandler.java
License:Apache License
@Override public void messageReceived(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception { Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new GenericFutureListener<Future<Channel>>() { @Override/*from w w w . ja v a 2 s . co m*/ public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType())) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { ctx.pipeline().remove(getName()); outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); ctx.channel().pipeline().addLast(new RelayHandler(outboundChannel)); } }); } else { ctx.channel() .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); final Channel inboundChannel = ctx.channel(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientInitializer(promise)); b.connect(request.host(), request.port()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results } else { // Close the connection if the connection attempt has failed. ctx.channel() .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); }
From source file:com.hazelcast.simulator.protocol.handler.ConnectionHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception { if (!(obj instanceof ByteBuf)) { return;//from w ww. jav a 2s. c o m } ByteBuf buf = (ByteBuf) obj; if (buf.readableBytes() < MINIMUM_BYTE_BUFFER_SIZE) { return; } if (!isSimulatorMessage(buf) && !isResponse(buf)) { LOGGER.warn(format("Invalid connection from %s (no magic bytes found)", ctx.channel().remoteAddress())); ctx.close(); return; } // the connection is valid so we remove this handler and forward the buffer to the pipeline LOGGER.info(format("Valid connection from %s (magic bytes found)", ctx.channel().remoteAddress())); isConnectionValid.countDown(); ctx.pipeline().remove(this); ctx.fireChannelRead(obj); ctx.channel().closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { connectionListener.disconnected(future.channel()); } }); connectionListener.connected(ctx.channel()); }
From source file:com.hazelcast.simulator.protocol.handler.ConnectionListenerHandler.java
License:Open Source License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.channel().closeFuture().addListener(new ChannelFutureListener() { @Override//from w ww. j a v a 2 s . co m public void operationComplete(ChannelFuture future) throws Exception { connectionListener.disconnected(future.channel()); } }); connectionListener.connected(ctx.channel()); }
From source file:com.heliosapm.webrpc.jsonservice.services.SystemJSONServices.java
License:Apache License
/** * Subscribes the calling channel to system status messages * @param request The request from the subscribing channel * <p>Invoker:<b><code>sendRemoteRequest('ws://localhost:4243/ws', {svc:'system', op:'subsysstat'});</code></b> *//*from w w w. j a va 2s .c o m*/ @JSONRequestHandler(name = "subsysstat", type = RequestType.SUBSCRIBE, description = "Subscribes the calling channel to system status messages") public void subscribeSystemStatus(final JSONRequest request) { if (systemStatusChannelGroup.add(request.channel)) { request.channel.closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { systemStatusRids.remove(future.channel()); } }); systemStatusRids.put(request.channel, request.requestId); ArrayNode arrNode = nodeFactory.arrayNode(); request.response(ResponseType.SUB_STARTED).setContent(arrNode).send(); } }
From source file:com.hipishare.chat.SecureChatClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE) .build();//from w ww . j a va 2 s . c o m EventLoopGroup group = new NioEventLoopGroup(); try { bootstrap = new Bootstrap(); bootstrap.group(group).channel(NioSocketChannel.class).handler(new SecureChatClientInitializer(sslCtx)); // Start the connection attempt. ChannelFuture channelFuture = bootstrap.connect(HOST, PORT).sync(); channel = channelFuture.channel(); // channel.closeFuture().sync(); // add reconnect listener reConnectListener = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { channel.close(); channel = future.channel(); LOG.info("???"); } else { LOG.info("??"); // 3?? future.channel().eventLoop().schedule(new Runnable() { @Override public void run() { reConnect(); } }, 3, TimeUnit.SECONDS); } } }; // Read commands from the stdin. ChannelFuture lastWriteFuture = null; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (;;) { String line = in.readLine(); if (line == null) { break; } // Sends the received line to the server. LOG.info("isActive=" + channel.isActive()); LOG.info("isOpen=" + channel.isOpen()); LOG.info("isWritable=" + channel.isWritable()); if (!channel.isOpen()) { reConnect(); } lastWriteFuture = channel.writeAndFlush("[channelId=" + channel.id() + "]" + line + "\r\n"); // If user typed the 'bye' command, wait until the server closes // the connection. if ("bye".equals(line.toLowerCase())) { channel.closeFuture().sync(); break; } } // Wait until all messages are flushed before closing the channel. if (lastWriteFuture != null) { lastWriteFuture.sync(); } } finally { // The connection is closed automatically on shutdown. group.shutdownGracefully(); } }
From source file:com.hipishare.chat.securetest.SecureChatClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE) .build();/*from ww w . j a va 2s . com*/ EventLoopGroup group = new NioEventLoopGroup(); try { bootstrap = new Bootstrap(); bootstrap.group(group).channel(NioSocketChannel.class).handler(new SecureChatClientInitializer(sslCtx)); // Start the connection attempt. ChannelFuture channelFuture = bootstrap.connect(HOST, PORT).sync(); channel = channelFuture.channel(); // add reconnect listener reConnectListener = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { channel.close(); channel = future.channel(); LOG.info("???"); } else { LOG.info("??"); // 3?? future.channel().eventLoop().schedule(new Runnable() { @Override public void run() { reConnect(); } }, 3, TimeUnit.SECONDS); } } }; // Read commands from the stdin. ChannelFuture lastWriteFuture = null; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (;;) { String line = in.readLine(); if (line == null) { break; } // Sends the received line to the server. if (!channel.isOpen()) { reConnect(); } MsgObject msgObj = new MsgObject(); Gson gson = new Gson(); if ("1".equals(line)) { User user = new User(); user.setAccount("peter"); user.setPwd("666666"); msgObj.setC(CmdEnum.LOGIN.getCmd()); msgObj.setM(gson.toJson(user)); } else if ("2".equals(line)) { ChatObject co = new ChatObject(); co.setContent("hello,jack. I am peter."); co.setMsgType("text"); co.setMsgTo("jack"); co.setMsgFrom("peter"); co.setCreateTime(System.currentTimeMillis()); msgObj.setC(CmdEnum.CHAT.getCmd()); msgObj.setM(gson.toJson(co)); } else if ("3".equals(line)) { RegisterCode rc = new RegisterCode(); rc.setMobile("13410969042"); rc.setSign("fdsafsadf"); msgObj.setC(CmdEnum.REGISTER_CODE.getCmd()); msgObj.setM(gson.toJson(rc)); } else if ("4".equals(line)) { RegisterCode rc = new RegisterCode(); rc.setMobile("13410969042"); rc.setCode("3243"); rc.setSign("fdsafsadf"); msgObj.setC(CmdEnum.REGISTER.getCmd()); msgObj.setM(gson.toJson(rc)); } String msg = gson.toJson(msgObj); ByteBuf buf = Unpooled.copiedBuffer(msg.getBytes()); lastWriteFuture = channel.writeAndFlush(buf); // If user typed the 'bye' command, wait until the server closes // the connection. if ("bye".equals(line.toLowerCase())) { channel.closeFuture().sync(); break; } } // Wait until all messages are flushed before closing the channel. if (lastWriteFuture != null) { lastWriteFuture.sync(); } channel.closeFuture().sync(); } finally { // The connection is closed automatically on shutdown. group.shutdownGracefully(); } }
From source file:com.hop.hhxx.example.factorial.FactorialClientHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, final BigInteger msg) { receivedMessages++;//w w w.j av a 2 s .c o m if (receivedMessages == io.netty.example.factorial.FactorialClient.COUNT) { // Offer the answer after closing the connection. ctx.channel().close().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { boolean offered = answer.offer(msg); assert offered; } }); } }
From source file:com.hop.hhxx.example.proxy.HexDumpProxyFrontendHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) { final Channel inboundChannel = ctx.channel(); // Start the connection attempt. Bootstrap b = new Bootstrap(); b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass()) .handler(new io.netty.example.proxy.HexDumpProxyBackendHandler(inboundChannel)) .option(ChannelOption.AUTO_READ, false); ChannelFuture f = b.connect(remoteHost, remotePort); outboundChannel = f.channel();/* w ww . j av a 2s . c om*/ f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { // connection complete start to read first data inboundChannel.read(); } else { // Close the connection if the connection attempt has failed. inboundChannel.close(); } } }); }