Example usage for io.netty.channel ChannelHandlerContext executor

List of usage examples for io.netty.channel ChannelHandlerContext executor

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext executor.

Prototype

EventExecutor executor();

Source Link

Document

Returns the EventExecutor which is used to execute an arbitrary task.

Usage

From source file:com.just.server.http.http.WebSocketFrameHandler.java

License:Apache License

@Override
protected void channelRead0(final ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
    // ping and pong frames already handled

    if (frame instanceof TextWebSocketFrame) {
        // Send the uppercase string back.
        String request = ((TextWebSocketFrame) frame).text();
        logger.info("{} received {}", ctx.channel(), request);
        if (request.equals("data")) {
            ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
            executorService.scheduleAtFixedRate(new CalculateEnvTask(), 0, timeInterval, TimeUnit.SECONDS);
            ctx.executor().scheduleAtFixedRate(new Runnable() {
                @Override/*from   w  w w  . j  a  v a 2s .c  o  m*/
                public void run() {
                    Environment env = null;
                    if ((env = CalculateEnvTask.cache.poll()) != null) {
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("ip", env.getIP());
                            jsonObject.put("netmask", env.getNetMask());
                            jsonObject.put("cpu", env.getCPUPercent());
                            jsonObject.put("mem", env.getMemPercent());
                            jsonObject.put("rx", env.getRxbps());
                            jsonObject.put("tx", env.getTxbps());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        ctx.channel().writeAndFlush(new TextWebSocketFrame(String.valueOf(jsonObject)));
                    }
                }
            }, 0, timeInterval, TimeUnit.SECONDS);
        }

    } else {
        String message = "unsupported frame type: " + frame.getClass().getName();
        throw new UnsupportedOperationException(message);
    }
}

From source file:com.lampard.netty4.protocol.netty.client.HeartBeatReqHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = (NettyMessage) msg;
    // ?????//  ww  w . jav a  2  s .c  o  m
    if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) {
        heartBeat = ctx.executor().scheduleAtFixedRate(new HeartBeatReqHandler.HeartBeatTask(ctx), 0, 5000,
                TimeUnit.MILLISECONDS);
    } else if (message.getHeader() != null
            && message.getHeader().getType() == MessageType.HEARTBEAT_RESP.value()) {
        LOG.info("Client receive server heart beat message : ---> " + message);
    } else
        ctx.fireChannelRead(msg);
}

From source file:com.linecorp.armeria.internal.ConnectionLimitingHandler.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    final Channel child = (Channel) msg;

    int conn = numConnections.incrementAndGet();
    if (conn > 0 && conn <= maxNumConnections) {
        childChannels.add(child);/*from w  w  w . java  2s  .  c o m*/
        child.closeFuture().addListener(future -> {
            childChannels.remove(child);
            numConnections.decrementAndGet();
        });
        super.channelRead(ctx, msg);
    } else {
        numConnections.decrementAndGet();

        // Set linger option to 0 so that the server doesn't get too many TIME_WAIT states.
        child.config().setOption(ChannelOption.SO_LINGER, 0);
        child.unsafe().closeForcibly();

        numDroppedConnections.increment();

        if (loggingScheduled.compareAndSet(false, true)) {
            ctx.executor().schedule(this::writeNumDroppedConnectionsLog, 1, TimeUnit.SECONDS);
        }
    }
}

From source file:com.look.netty.demo.socksproxy.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception {
    if (message instanceof Socks4CommandRequest) {
        final Socks4CommandRequest request = (Socks4CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            @Override//from  ww w  . j  ava 2s. c  o m
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel()
                            .writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS));

                    responseFuture.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    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 DirectClientHandler(promise));

        b.connect(request.dstAddr(), request.dstPort()).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 DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else if (message instanceof Socks5CommandRequest) {
        final Socks5CommandRequest request = (Socks5CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            @Override
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(
                            Socks5CommandStatus.SUCCESS, request.dstAddrType()));

                    responseFuture.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    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 DirectClientHandler(promise));

        b.connect(request.dstAddr(), request.dstPort()).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 DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else {
        ctx.close();
    }
}

From source file:com.mongodb.connection.netty.ReadTimeoutHandler.java

License:Apache License

void scheduleTimeout(final ChannelHandlerContext ctx) {
    isTrue("Handler called from the eventLoop", ctx.channel().eventLoop().inEventLoop());
    if (timeout == null) {
        timeout = ctx.executor().schedule(new ReadTimeoutTask(ctx), readTimeout, TimeUnit.MILLISECONDS);
    }// w  ww .ja  va 2s. c  o m
}

From source file:com.phei.netty.protocol.netty.client.HeartBeatReqHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = (NettyMessage) msg;
    // ?????//from   w  ww .  j  av a  2s  .  c  o  m
    if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) {
        //5???
        heartBeat = ctx.executor().scheduleAtFixedRate(new HeartBeatReqHandler.HeartBeatTask(ctx), 0, 5000,
                TimeUnit.MILLISECONDS);
    } else if (message.getHeader() != null
            && message.getHeader().getType() == MessageType.HEARTBEAT_RESP.value()) {
        System.out.println("Client receive server heart beat message : ---> " + message);
    } else {
        ctx.fireChannelRead(msg);
    }
}

From source file:com.siondream.superjumper.net.SecureChatServerHandler.java

License:Apache License

ScheduledFuture<?> schedule(ChannelHandlerContext ctx, Runnable task, long delay, TimeUnit unit) {
    return ctx.executor().schedule(task, delay, unit);
}

From source file:com.spotify.netty.handler.queue.AutoFlushingWriteBatcher.java

License:Apache License

/**
 * Called when the channel is opened./*from   w  w w.  j a v  a  2s.c  om*/
 */
@Override
public void connect(final ChannelHandlerContext ctx, SocketAddress remote, SocketAddress local,
        ChannelPromise promise) throws Exception {
    // Schedule a task to flush and enforce the maximum latency that a message is buffered
    flushFuture = ctx.executor().scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            final long nanosSinceLastFlush = System.nanoTime() - lastFlush;
            if (nanosSinceLastFlush > maxDelayNanos) {
                ctx.flush();
                bufferSize.set(0);
                lastFlush = System.nanoTime();
            }
        }
    }, intervalNanos, intervalNanos, NANOSECONDS);

    ctx.connect(remote, local, promise);
}

From source file:com.tesora.dve.server.connectionmanager.loaddata.MSPLoadDataDecoder.java

License:Open Source License

private void clientThreadInsertSuccess(final ChannelHandlerContext ctx) {

    ctx.executor().submit(new Callable<Void>() {
        @Override//from www  . j  a  v  a  2 s. c  o  m
        public Void call() throws Exception {
            insertSuccess(ctx);
            return null;
        }
    });
}

From source file:com.tesora.dve.server.connectionmanager.loaddata.MSPLoadDataDecoder.java

License:Open Source License

private void clientThreadInsertFailure(final ChannelHandlerContext ctx, final Throwable e) {
    ctx.executor().submit(new Callable<Void>() {
        @Override/* ww w.j a v a2  s. c  o m*/
        public Void call() throws Exception {
            insertFailure(ctx, e);
            return null;
        }
    });

}