Example usage for io.netty.channel ChannelFuture addListener

List of usage examples for io.netty.channel ChannelFuture addListener

Introduction

In this page you can find the example usage for io.netty.channel ChannelFuture addListener.

Prototype

@Override
    ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);

Source Link

Usage

From source file:me.ferrybig.p2pnetwork.Main.java

private void startOutgomingConnectionThread(InetAddress address, int port) {
    Bootstrap client = new Bootstrap();
    client.group(group);// ww  w.j  a  v  a  2  s. c o  m
    client.channel(NioSocketChannel.class);
    client.option(ChannelOption.SO_KEEPALIVE, true);
    client.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new LengthFieldPrepender(4));
            ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
            ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
            ch.pipeline().addLast(new PacketEncoder());
            ch.pipeline().addLast(new PacketDecoder());
            ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
            ch.pipeline().addLast(new ServerBootstrapConnector(addr, outgoingListener));
        }
    });
    ChannelFuture f = client.connect(address, port);
    f.addListener(e -> {
        this.clientsOut.add(f.channel());
        f.channel().closeFuture().addListener(e1 -> {
            this.clientsOut.remove(f.channel());
        });
    });
}

From source file:me.ferrybig.p2pnetwork.Peer.java

public ChannelFuture startIncomingConnectionThread(int port) {
    ServerBootstrap server = new ServerBootstrap();
    server.group(group);/* w w w .j  a  v a  2  s . co m*/
    server.channel(NioServerSocketChannel.class);
    server.option(ChannelOption.SO_BACKLOG, 128);
    server.childOption(ChannelOption.SO_KEEPALIVE, true);
    server.childHandler(new ChannelConstructor(incomingListener, clientsIn));
    ChannelFuture f = server.bind(port);
    return f.addListener(e -> {
        if (e.isSuccess()) {
            this.servers.add((ServerChannel) f.channel());
            f.channel().closeFuture().addListener(e1 -> {
                this.servers.remove((ServerChannel) f.channel());
            });
        }
    });
}

From source file:me.ferrybig.p2pnetwork.Peer.java

public ChannelFuture startOutgomingConnectionThread(InetAddress address, int port) {
    Bootstrap client = new Bootstrap();
    client.group(group);//from   w w  w .  j a  v a2  s. co  m
    client.channel(NioSocketChannel.class);
    client.option(ChannelOption.SO_KEEPALIVE, true);
    client.handler(new ChannelConstructor(outgoingListener, clientsOut));
    ChannelFuture f = client.connect(address, port);
    return f.addListener(e -> {
        this.clientsOut.add(f.channel());
        f.channel().closeFuture().addListener(e1 -> {
            this.clientsOut.remove(f.channel());
        });
    });
}

From source file:me.hrps.rp.preview.chat.service.WebSocketServerHandler.java

License:Apache License

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
    Channel chn = ctx.channel();/*from   w  w  w.j ava  2  s.  c  om*/
    String chnId = chn.id().toString();
    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        return;
    }
    if (frame instanceof PingWebSocketFrame) {
        ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
        return;
    }
    if (!(frame instanceof TextWebSocketFrame)) {
        throw new UnsupportedOperationException(
                String.format("%s frame types not supported", frame.getClass().getName()));
    }

    // Send the uppercase string back.
    String request = ((TextWebSocketFrame) frame).text().toLowerCase();
    //MSG=&FROM=4&TO=%235&TYPING=TRUE  
    //MSG=222&FROM=4&TO=%235&TYPING=FALSE   ?
    if (request != null && request.startsWith("msg")) {
        request = Encodes.urlDecode(request.toLowerCase());
        String[] reqMsg = request.split("&");
        Message msg = new Message();
        for (String input : reqMsg) {
            String[] inputvalue = input.split("=");
            if (inputvalue.length == 2)
                ReflectionUtils.invokeSetter(msg, inputvalue[0], inputvalue[1]);
        }
        Channel toChannel = WebSocketServerInitializer.chs.get(msg.getChannelid());

        //??
        if ("false".equals(msg.getTyping())) {
            if (msg.getTo() != null) {
                msg.setTo(msg.getTo().replace("#", ""));
            }
            MetaData chatMsgInfo = new MetaData();
            chatMsgInfo.setType(2);
            chatMsgInfo.setMsg(msg);
            if (toChannel.isActive()) {
                String pushChatInfo = JacksonMapper.toJSONString(chatMsgInfo);
                toChannel.writeAndFlush(new TextWebSocketFrame(pushChatInfo));
            }
        }
        return;
    }

    MetaData md = JacksonMapper.readValue(request, MetaData.class);
    //??,??
    if (WebSocketServerInitializer.mds.get(chnId) == null && md != null && md.getType() == 3) {
        PreChatUser user = chatUserMapper.selectByPrimaryKey(md.getUser().getId());
        user.setChannelid(chnId);
        if (user != null)
            md.setUser(user);
        WebSocketServerInitializer.mds.put(chnId, md);
        //??,
        MetaData onlineMemberInfo = new MetaData();
        onlineMemberInfo.setType(1);
        List<PreChatUser> users = Lists.newArrayList();
        Iterator<MetaData> it = WebSocketServerInitializer.mds.values().iterator();
        while (it.hasNext()) {
            MetaData onlineUser = it.next();
            users.add(onlineUser.getUser());
        }
        onlineMemberInfo.setUsers(users);
        String pushOnlineInfo = JacksonMapper.toJSONString(onlineMemberInfo);
        Iterator<Channel> chnItor = WebSocketServerInitializer.chs.values().iterator();
        while (chnItor.hasNext()) {
            Channel currChn = chnItor.next();
            if (currChn.isActive()) {
                currChn.writeAndFlush(new TextWebSocketFrame(pushOnlineInfo));
            }
        }
        return;
    }

    System.err.printf("%s received %s%n", ctx.channel(), request);
    ChannelFuture f = ctx.channel().write(new TextWebSocketFrame(request.toUpperCase()));
    if ("bye".equals(request)) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:me.jesonlee.jjfsserver.httpserver.HttpStaticFileServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);/*from w w  w  .j  ava 2s .c o  m*/
        return;
    }

    if (request.getMethod() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }

    final String uri = request.getUri();
    final String path = PathUtil.sanitizeUri(uri);
    if (path == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    File file = new File(path);
    if (file.isHidden() || !file.exists()) {
        sendError(ctx, NOT_FOUND);
        return;
    }

    if (file.isDirectory()) {
        if (uri.endsWith("/")) {
            sendListing(ctx, file);
        } else {
            sendRedirect(ctx, uri + '/');
        }
        return;
    }

    if (!file.isFile()) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    // Cache Validation
    String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
        Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);

        // Only compare up to the second because the datetime format we send to the client
        // does not have milliseconds
        long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
        long fileLastModifiedSeconds = file.lastModified() / 1000;
        if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
            sendNotModified(ctx);
            return;
        }
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException ignore) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    HttpHeaders.setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    if (HttpHeaders.isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the initial line and the header.
    ctx.write(response);

    // Write the content.
    ChannelFuture sendFileFuture;
    ChannelFuture lastContentFuture;
    if (ctx.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());
        // Write the end marker.
        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    } else {
        sendFileFuture = ctx.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                ctx.newProgressivePromise());
        // HttpChunkedInput will write the end marker (LastHttpContent) for us.
        lastContentFuture = sendFileFuture;
    }

    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
            if (total < 0) { // total unknown
                System.err.println(future.channel() + " Transfer progress: " + progress);
            } else {
                System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) {
            System.err.println(future.channel() + " Transfer complete.");
        }
    });

    // Decide whether to close the connection or not.
    if (!HttpHeaders.isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:me.zhuoran.amoeba.netty.server.HttpServerHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, FullHttpResponse res) {
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);/*from  w  w  w . j a  v a 2 s  . co m*/
        buf.release();
        HttpHeaders.setContentLength(res, (long) res.content().readableBytes());
    }

    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }

}

From source file:nearenough.examples.NettyClient.java

License:Open Source License

public static void main(String[] args) throws InterruptedException {
    InetSocketAddress addr = new InetSocketAddress(INT08H_SERVER_HOST, INT08H_SERVER_PORT);

    System.out.printf("Sending request to %s\n", addr);

    // Below is Netty boilerplate for setting-up an event loop and registering a handler
    NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap().group(nioEventLoopGroup).remoteAddress(addr)
            .channel(NioDatagramChannel.class).handler(new ChannelInitializer<NioDatagramChannel>() {
                @Override/*from  ww  w .j a  v  a  2s  .co m*/
                protected void initChannel(NioDatagramChannel ch) {
                    ch.pipeline().addLast(new ReadTimeoutHandler(5)).addLast(new RequestHandler(addr));
                }
            });

    ChannelFuture connectFuture = bootstrap.connect();
    connectFuture.addListener(future -> {
        if (!future.isSuccess()) {
            System.out.println("Connect fail:");
            System.out.println(future.cause().getMessage());
        }
    });

    connectFuture.channel().closeFuture().sync();
    nioEventLoopGroup.shutdownGracefully();
}

From source file:net.dongliu.prettypb.rpc.server.RequestHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, WirePayload msg, List<Object> out) throws Exception {
    if (msg.hasConnectRequest()) {
        ConnectRequest connectRequest = msg.getConnectRequest();
        logger.info("Received ConnectRequest from {}:{}, use compress: {}.", connectRequest.getClientHostName(),
                connectRequest.getClientPort(), connectRequest.isCompress());
        PeerInfo clientInfo = new PeerInfo(connectRequest.getClientHostName(), connectRequest.getClientPort(),
                connectRequest.getClientPID());
        ConnectResponse connectResponse;

        RpcServerChannel rpcServerChannel = new RpcServerChannel(ctx.channel(), serverPeer, clientInfo,
                connectRequest.isCompress());
        if (rpcServerChannelRegistry.registerRpcServerChannel(rpcServerChannel)) {
            connectResponse = new ConnectResponse();
            connectResponse.setCorrelationId(connectRequest.getCorrelationId());
            connectResponse.setServerPID(serverPeer.getPid());
            connectResponse.setCompress(connectRequest.isCompress());
            WirePayload payload = new WirePayload();
            payload.setConnectResponse(connectResponse);
            ctx.channel().writeAndFlush(payload);

            completePipeline(rpcServerChannel);
        } else {//from w  w w  .j  a v  a  2 s  . c om
            connectResponse = new ConnectResponse();
            connectResponse.setCorrelationId(connectRequest.getCorrelationId());
            connectResponse.setErrorCode(ConnectErrorCode.ALREADY_CONNECTED);
            WirePayload payload = new WirePayload();
            payload.setConnectResponse(connectResponse);

            logger.debug("Sending ConnectResponse({}). Already Connected.", connectResponse.getCorrelationId());
            ChannelFuture future = ctx.channel().writeAndFlush(payload);
            future.addListener(ChannelFutureListener.CLOSE); // close after write response.
        }
    } else {
        out.add(msg);
    }
}

From source file:net.epsilony.utils.codec.modbus.ModbusClientMaster.java

License:Open Source License

public CompletableFuture<ModbusResponse> request(ModbusRequest req) {
    final CompletableFuture<ModbusResponse> result = new CompletableFuture<>();

    result.whenComplete((res, ex) -> {
        if (transectionIdDispatcher != null) {
            int transectionId = req.getTransectionId();
            if (transectionId >= 0) {
                transectionIdDispatcher.repay(transectionId);
            }//w ww  .j a  v  a2s. com
        }
    });

    lock.lock();
    try {
        if (connectFuture == null) {
            connectFuture = genConnectFuture();
            connectFuture.addListener(new GenericFutureListener<Future<? super Void>>() {

                @Override
                public void operationComplete(Future<? super Void> future) throws Exception {
                    lock.lock();
                    try {
                        if (future.isSuccess()) {
                            channel = connectFuture.channel();
                            channel.closeFuture()
                                    .addListener(new GenericFutureListener<Future<? super Void>>() {

                                        @Override
                                        public void operationComplete(Future<? super Void> future)
                                                throws Exception {
                                            lock.lock();
                                            try {
                                                connectFuture = null;
                                                initializer.clearExceptionally(
                                                        new ConnectException("connection is closed!"));
                                                transectionIdDispatcher.reset();
                                            } finally {
                                                lock.unlock();
                                            }
                                        }
                                    });
                        } else {
                            connectFuture = null;
                        }
                    } finally {
                        lock.unlock();
                    }
                }
            });
        }

        connectFuture.addListener(new GenericFutureListener<Future<? super Void>>() {

            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                ChannelFuture channelFuture = (ChannelFuture) future;
                if (future.isSuccess()) {
                    if (null != transectionIdDispatcher) {
                        int transectionId = transectionIdDispatcher.borrow();
                        req.setTransectionId(transectionId);
                        if (transectionId < 0) {
                            result.completeExceptionally(new TransectionDispatcherEmptyException());
                            return;
                        }
                    }

                    try {
                        initializer.register(result, req);
                    } catch (Throwable ex) {
                        result.completeExceptionally(ex);
                        return;
                    }

                    ChannelFuture writeFuture = channelFuture.channel().writeAndFlush(req);
                    writeFuture.addListener(new GenericFutureListener<Future<? super Void>>() {

                        @Override
                        public void operationComplete(Future<? super Void> future) throws Exception {
                            if (!future.isSuccess()) {
                                if (future.isCancelled()) {
                                    initializer.removeExceptionally(req.getTransectionId(),
                                            new ConnectException("connection is canncelled"));
                                } else {
                                    initializer.removeExceptionally(req.getTransectionId(), future.cause());
                                }
                            }
                        }
                    });
                } else if (future.isCancelled()) {
                    result.completeExceptionally(new ConnectException("connection is canncelled"));
                } else {
                    result.completeExceptionally(future.cause());
                }
            }

        });
    } finally {
        lock.unlock();
    }

    return result;

}

From source file:net.hasor.rsf.console.TelnetHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, String request) throws Exception {
    request = request.trim();//  w  ww. j  a v  a2s. c o m
    rxdLogger.info("RXD({})-> {}", ctx.channel().remoteAddress(), request);
    //
    Attribute<RsfCommandRequest> attr = ctx.attr(RequestKEY);
    boolean close = false;
    String result = "";
    boolean doRequest = false;
    if (StringUtils.isBlank(request)) {
        if (attr != null && attr.get() != null) {
            doRequest = true;
        }
    } else {
        doRequest = true;
    }
    //
    if (!doRequest) {
        logger.info("rsfConsole -> receive RXD :" + request);
    }
    //
    if (doRequest) {
        RsfCommandResponse response = this.doRequest(attr, ctx, request);
        if (response != null) {
            close = response.isCloseConnection();
            logger.info("rsfConsole -> receive RXD, response isComplete = {}, isCloseConnection = {}",
                    response.isComplete(), response.isCloseConnection());
            if (response.isComplete()) {
                result = response.getResult() + "\r\n" + CMD;
            } else {
                result = response.getResult() + "\r\n";
            }
        }
    } else {
        result = CMD;
    }
    //
    if (StringUtils.isNotBlank(result)) {
        rxdLogger.info("TXD({})-> {}", ctx.channel().remoteAddress(), result);
        ChannelFuture future = ctx.writeAndFlush(result);
        if (close) {
            logger.info("rsfConsole -> close connection.");
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }
}