Example usage for io.netty.handler.timeout ReadTimeoutHandler ReadTimeoutHandler

List of usage examples for io.netty.handler.timeout ReadTimeoutHandler ReadTimeoutHandler

Introduction

In this page you can find the example usage for io.netty.handler.timeout ReadTimeoutHandler ReadTimeoutHandler.

Prototype

public ReadTimeoutHandler(int timeoutSeconds) 

Source Link

Document

Creates a new instance.

Usage

From source file:divconq.bus.Bus.java

License:Open Source License

public void connect() {
    // never try to connect until init has run
    if (Hub.instance.isStopping())
        return;//from   w ww.  ja va  2  s.  c o  m

    // if connect method is already running then skip - it will try again later 
    if (!this.connectLock.tryLock())
        return;

    try {
        // ==========================================================================
        //   Add client connections when not enough
        // ==========================================================================

        for (final SocketInfo info : this.connectors.values()) {
            HubRouter router = this.allocateOrGetHub(info.getHubId(), info.isGateway());

            if (router.isLocal())
                continue;

            // -------------------------------------------------
            // message port
            // -------------------------------------------------
            int conncount = router.getCountSessions(info);

            // add a coonection only once per call to connect (should be between 2 - 15 seconds between calls)
            if (conncount < info.getCount()) {
                Bootstrap b = new Bootstrap();

                b.group(this.getEventLoopGroup()).channel(NioSocketChannel.class)
                        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 250)
                        .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            public void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline pipeline = ch.pipeline();

                                if (info.isUseSsl())
                                    pipeline.addLast("ssl",
                                            new SslHandler(SslContextFactory.getClientEngine()));

                                pipeline.addLast("http-codec", new HttpClientCodec());
                                pipeline.addLast("aggregator", new HttpObjectAggregator(8192)); // TODO is this too small?

                                pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60)); // TODO config
                                pipeline.addLast("writeTimeoutHandler", new WriteTimeoutHandler(30)); // TODO config

                                pipeline.addLast("ws-handler", new ClientHandler(info));
                            }
                        });

                Logger.debug("dcBus Client connecting");

                try {
                    // must wait here to make sure we don't release connectLock too soon
                    // we want channel init (above) to complete before we try connect again
                    b.connect(info.getAddress()).sync();
                } catch (InterruptedException x) {
                    Logger.warn("dcBus Client interrupted while connecting: " + x);
                } catch (Exception x) {
                    Logger.debug("dcBus Client unable to connect: " + x);
                }
            }

            // -------------------------------------------------
            // stream port
            // -------------------------------------------------
            conncount = router.getCountStreamSessions(info);

            // add a coonection only once per call to connect (should be between 2 - 15 seconds between calls)
            if (conncount < info.getStreamCount()) {
                Bootstrap b = new Bootstrap();

                b.group(this.getEventLoopGroup()).channel(NioSocketChannel.class)
                        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 250)
                        .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            public void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline pipeline = ch.pipeline();

                                if (info.isUseSsl())
                                    pipeline.addLast("ssl",
                                            new SslHandler(SslContextFactory.getClientEngine()));

                                // TODO consider compression

                                pipeline.addLast("decoder", new StreamDecoder());
                                pipeline.addLast("encoder", new StreamEncoder());

                                pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60)); // TODO config
                                pipeline.addLast("writeTimeoutHandler", new WriteTimeoutHandler(30)); // TODO config

                                pipeline.addLast("handler", new StreamHandler(info, false));
                            }
                        });

                Logger.debug("dcBus Client stream connecting");

                try {
                    // must wait here to make sure we don't release connectLock too soon
                    // we want chanel init (above) to complete before we try connect again
                    b.connect(info.getStreamAddress()).addListener(new GenericFutureListener<ChannelFuture>() {
                        @Override
                        public void operationComplete(ChannelFuture cf) throws Exception {
                            if (!cf.isSuccess()) {
                                Logger.debug("dcBus Stream unable to connect: " + cf.cause());
                                return;
                            }

                            // client starts the HELLO thing once connected!
                            StreamMessage icmd = Hub.instance.getBus().getLocalHub()
                                    .buildStreamHello(info.getHubId());
                            cf.channel().writeAndFlush(icmd);
                        }
                    }).sync();
                } catch (InterruptedException x) {
                    Logger.warn("dcBus Client stream interrupted while connecting: " + x);
                } catch (Exception x) {
                    Logger.debug("dcBus Client stream unable to connect: " + x);
                }
            }
        }

        // ==========================================================================
        //   Add server binding when missing
        // ==========================================================================

        for (final SocketInfo info : this.listeners) {
            // only if not currently bound
            if (this.activelisteners.containsKey(info))
                continue;

            // -------------------------------------------------
            // message port
            // -------------------------------------------------
            ServerBootstrap b = new ServerBootstrap();

            b.group(this.getEventLoopGroup()).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
                    //.option(ChannelOption.SO_BACKLOG, 125)         // this is probably not needed but serves as note to research
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            if (info.isUseSsl())
                                pipeline.addLast("ssl", new SslHandler(SslContextFactory.getServerEngine()));

                            pipeline.addLast("codec-http", new HttpServerCodec());
                            pipeline.addLast("aggregator", new HttpObjectAggregator(65536));

                            pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60)); // TODO config
                            pipeline.addLast("writeTimeoutHandler", new WriteTimeoutHandler(30)); // TODO config

                            pipeline.addLast("handler", new ServerHandler(info));
                        }
                    });

            try {
                // must wait here, both to keep the activelisteners listeners up to date
                // but also to make sure we don't release connectLock too soon
                ChannelFuture bfuture = b.bind(info.getAddress()).sync();

                if (bfuture.isSuccess()) {
                    Logger.info("dcBus Message Server listening - now listening for dcMessages on TCP port "
                            + info.getPort());
                    this.activelisteners.put(info, bfuture.channel());
                } else
                    Logger.error("dcBus Server unable to bind: " + bfuture.cause());
            } catch (InterruptedException x) {
                Logger.warn("dcBus Server interrupted while binding: " + x);
            } catch (Exception x) {
                Logger.error("dcBus Server unable to bind: " + x);
            }

            // -------------------------------------------------
            // stream port
            // -------------------------------------------------
            b = new ServerBootstrap();

            b.group(this.getEventLoopGroup()).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
                    //.option(ChannelOption.SO_BACKLOG, 125)         // this is probably not needed but serves as note to research
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            if (info.isUseSsl())
                                pipeline.addLast("ssl", new SslHandler(SslContextFactory.getServerEngine()));

                            // TODO consider compression

                            pipeline.addLast("decoder", new StreamDecoder());
                            pipeline.addLast("encoder", new StreamEncoder());

                            pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60)); // TODO config
                            pipeline.addLast("writeTimeoutHandler", new WriteTimeoutHandler(30)); // TODO config

                            pipeline.addLast("handler", new StreamHandler(info, true));
                        }
                    });

            try {
                // must wait here, both to keep the activelisteners listeners up to date
                // but also to make sure we don't release connectLock too soon
                ChannelFuture bfuture = b.bind(info.getStreamAddress()).sync();

                if (bfuture.isSuccess()) {
                    Logger.info("dcBus Stream Server listening - now listening for dcStreams on TCP port "
                            + info.getPort());
                    this.activestreamlisteners.put(info, bfuture.channel());
                } else
                    Logger.error("dcBus Stream Server unable to bind: " + bfuture.cause());
            } catch (InterruptedException x) {
                Logger.warn("dcBus Stream Server interrupted while binding: " + x);
            } catch (Exception x) {
                Logger.error("dcBus Stream Server unable to bind: " + x);
            }
        }

        // ==========================================================================
        //   Remove server binding as needed
        // ==========================================================================

        for (final SocketInfo info : this.activelisteners.keySet()) {
            // all is well if in the listeners list
            if (this.listeners.contains(info))
                continue;

            // otherwise we don't want to bind anymore
            this.stopSocketListener(info);
        }
    } finally {
        this.connectLock.unlock();
    }
}

From source file:divconq.ctp.net.CtpServices.java

License:Open Source License

public void connect() {
    // never try to connect until init has run
    if (Hub.instance.isStopping())
        return;//  w w  w  . j ava2 s .  c  o m

    // if connect method is already running then skip - it will try again later 
    if (!this.connectLock.tryLock())
        return;

    try {
        // ==========================================================================
        //   Add server binding when missing
        // ==========================================================================

        for (SocketInfo info : this.listeners) {
            // only if not currently bound
            if (this.activelisteners.containsKey(info))
                continue;

            // -------------------------------------------------
            // stream port
            // -------------------------------------------------
            ServerBootstrap b = new ServerBootstrap().group(Hub.instance.getEventLoopGroup())
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
                    //.option(ChannelOption.SO_BACKLOG, 125)         // this is probably not needed but serves as note to research
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            if (info.isUseSsl())
                                pipeline.addLast("ssl", new SslHandler(SslContextFactory.getServerEngine())); // TODO this should be the external SSL not the BUS one 

                            pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60)); // TODO config
                            pipeline.addLast("writeTimeoutHandler", new WriteTimeoutHandler(45)); // TODO config

                            //pipeline.addLast("logger", new LoggingHandler(LogLevel.INFO));

                            // start as guest until authenticated
                            CtpAdapter adapter = new CtpAdapter(OperationContext.allocateGuest());
                            adapter.setHandler(new CtpsHandler());

                            pipeline.addLast("ctp", new CtpHandler(adapter, true));
                        }
                    });

            try {
                // must wait here, both to keep the activelisteners listeners up to date
                // and also to make sure we don't release connectLock too soon
                ChannelFuture bfuture = b.bind(info.getAddress()).sync();

                if (bfuture.isSuccess()) {
                    Logger.info("dcCtp Server listening");
                    this.activelisteners.put(info, bfuture.channel());
                } else
                    Logger.error("dcCtp Server unable to bind: " + bfuture.cause());
            } catch (InterruptedException x) {
                Logger.warn("dcCtp Server interrupted while binding: " + x);
            } catch (Exception x) {
                Logger.error("dcCtp Server unable to bind: " + x);
            }
        }

        // ==========================================================================
        //   Remove server binding as needed
        // ==========================================================================

        for (final SocketInfo info : this.activelisteners.keySet()) {
            // all is well if in the listeners list
            if (this.listeners.contains(info))
                continue;

            // otherwise we don't want to bind anymore
            this.stopSocketListener(info);
        }
    } finally {
        this.connectLock.unlock();
    }
}

From source file:eu.jangos.realm.RealmServer.java

License:Apache License

/**
 * Main of the RealmServer program./*from   w w  w .  j av a2 s .  com*/
 *
 * @param args the command line arguments
 * @throws InterruptedException in case of interruption of the running
 * process.
 */
public static void main(String[] args) throws InterruptedException {

    logger.info("Starting JaNGOS realm server version " + VERSION + ".");
    logger.info("JaNGOS is an opensource project, check-out : https://github.com/Warkdev/JaNGOSRealm !");

    realm.setOffline(false);
    rs.save(realm);

    logger.info("Realm configuration: ");
    logger.info("Name: " + realm.getName());
    logger.info("Address: " + realm.getAddress() + ":" + realm.getPort());
    logger.info("Type: " + realm.getRealmtype().getType());
    logger.info("Timezone: " + realm.getRealmtimezone().getName());
    logger.info("Population: " + realm.getPopulation());
    logger.info("Players: " + realm.getCountPlayers() + "/" + realm.getMaxPlayers());

    // 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).option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new RealmPacketDecoder(), new RealmPacketEncoder(), new RealmAuthHandler(),
                                new ReadTimeoutHandler(TIMEOUT), new CharacterHandler());
                    }
                });

        ChannelFuture f;

        // Start the server.   
        try {
            HOST = InetAddress.getByAddress(realm.getAddress().getBytes());
            f = b.bind(HOST, PORT).sync();
            logger.info("JaNGOS realm server started listening on " + HOST.getHostAddress() + ":" + PORT);
        } catch (UnknownHostException ex) {
            f = b.bind(PORT);
            logger.info("JaNGOS realm server started listening on port " + PORT);
        }

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        logger.info("JaNGOS realm server shutting down.");

        // Indicating that this realm is offline.
        realm.setOffline(true);
        rs.save(realm);

        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:eu.point.client.Client.java

License:Open Source License

/**
 * The method which creates the bootstrap to connect to the server.
 * It initializes the pipeline with all the required parameters and functions
 * for encoding, decoding, etc./* w  w w  .  j  a  va  2 s .  c o  m*/
 * It then sends the message to the server.
 * If the message is a Resource Request, then it also returns the received Resource Offer.
 *
 * @param message The message to be sent.
 * @return The received Resource Offer in case the message was a Resource Request.
 */
public static TmSdnMessages.TmSdnMessage.ResourceOfferMessage sendMessage(TmSdnMessages.TmSdnMessage message) {
    EventLoopGroup group = new NioEventLoopGroup();
    TmSdnMessages.TmSdnMessage.ResourceOfferMessage resourceOffer = null;
    handler = new TmSdnClientHandler(message);
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, false);
        //initialize the pipeline
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();

                pipeline.addLast(new ProtobufVarint32FrameDecoder());
                pipeline.addLast(new ProtobufDecoder(TmSdnMessages.TmSdnMessage.getDefaultInstance()));
                pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());
                pipeline.addLast(new ProtobufEncoder());
                pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(5));

                pipeline.addLast(handler);
            }
        });

        // Make a new connection.
        ChannelFuture f = b.remoteAddress(serverIP, tcpPort).connect();
        try {
            f.sync();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //if message is resource request, then get the received resource offer and return it.
        if (f.isSuccess() && message.getType() == TmSdnMessages.TmSdnMessage.TmSdnMessageType.RR) {
            TmSdnMessages.TmSdnMessage.ResourceOfferMessage resp = handler.resultQueue.take();
            if (resp != null) {
                resourceOffer = resp;
            }
        }
        //close the channel.
        f.channel().closeFuture().sync();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        group.shutdownGracefully();
    }
    return resourceOffer;
}

From source file:favoorr.netty.protocol.netty.server.NettyServer.java

License:Apache License

public void bind() throws Exception {
    // ??NIO/*from w  ww .  j a v a  2 s .c om*/
    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 f = b.bind(NettyConstant.REMOTEIP, NettyConstant.PORT).sync();

    System.out.println("Netty server start ok : " + (NettyConstant.REMOTEIP + " : " + NettyConstant.PORT));

    f.channel().closeFuture().sync();
}

From source file:herddb.network.netty.NettyConnector.java

License:Apache License

public static NettyChannel connect(String host, int port, boolean ssl, int connectTimeout, int socketTimeout,
        ChannelEventListener receiver, final ExecutorService callbackExecutor,
        final MultithreadEventLoopGroup networkGroup, final DefaultEventLoopGroup localEventsGroup)
        throws IOException {
    try {//from   w ww.j  a  v a  2  s . c  om
        final SslContext sslCtx = !ssl ? null
                : SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();

        Class<? extends Channel> channelType;

        InetSocketAddress inet = new InetSocketAddress(host, port);
        SocketAddress address;
        String hostAddress = NetworkUtils.getAddress(inet);

        MultithreadEventLoopGroup group;
        if (LocalServerRegistry.isLocalServer(hostAddress, port, ssl)) {
            channelType = LocalChannel.class;
            address = new LocalAddress(hostAddress + ":" + port + ":" + ssl);
            group = localEventsGroup;
        } else {
            channelType = networkGroup instanceof EpollEventLoopGroup ? EpollSocketChannel.class
                    : NioSocketChannel.class;
            address = inet;
            group = networkGroup;
        }
        Bootstrap b = new Bootstrap();
        AtomicReference<NettyChannel> result = new AtomicReference<>();

        b.group(group).channel(channelType).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    public void initChannel(Channel ch) throws Exception {
                        try {
                            NettyChannel channel = new NettyChannel(host + ":" + port, ch, callbackExecutor);
                            result.set(channel);
                            channel.setMessagesReceiver(receiver);
                            if (ssl) {
                                ch.pipeline().addLast(sslCtx.newHandler(ch.alloc(), host, port));
                            }
                            if (socketTimeout > 0) {
                                ch.pipeline().addLast("readTimeoutHandler",
                                        new ReadTimeoutHandler(socketTimeout));
                            }
                            ch.pipeline().addLast("lengthprepender", new LengthFieldPrepender(4));
                            ch.pipeline().addLast("lengthbaseddecoder",
                                    new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                            //
                            ch.pipeline().addLast("messagedecoder", new ProtocolMessageDecoder());
                            ch.pipeline().addLast(new ClientInboundMessageHandler(channel));
                        } catch (Throwable t) {
                            LOGGER.log(Level.SEVERE, "error connecting", t);
                            ch.close();
                        }
                    }
                });

        LOGGER.log(Level.FINE, "connecting to {0}:{1} ssl={2} address={3}",
                new Object[] { host, port, ssl, address });
        b.connect(address).sync();
        NettyChannel nettyChannel = result.get();
        if (!nettyChannel.isValid()) {
            throw new IOException("returned channel is not valid");
        }
        return nettyChannel;
    } catch (InterruptedException ex) {
        throw new IOException(ex);
    }

}

From source file:in.voidma.lemming.Lemming.java

License:Open Source License

@Override
public void onLoad() {

    getLogger().log(Level.ALL, "LoadingLemming");

    // Logging//w  ww  . j  a va  2 s  .co m
    logger = getLogger();
    LemmingLogger.init(this);

    // Configuration
    saveDefaultConfig();
    reloadConfig();

    try {
        config = new LemmingConfig(this);
    } catch (Exception e) {
        // TODO: Add warnings
    }

    // Print the state of the debug mode
    if (config.isServerDebug()) {
        logger.warning("Server side debug mode is enabled!");
    }

    // And the state of the error reporter
    if (config.isServerDetailedErrorReporting()) {
        // TODO: Enable detailed reporting
        logger.warning("Server side detailed error reporting enabled!");
    }

    // ProtocolLib setup
    manager = ProtocolLibrary.getProtocolManager();

    InternalManager manager = new InternalManager();

    LemmingLibrary.init(this, config, manager);

    DedicatedServer server = (DedicatedServer) getServer();
    final ServerConnection serverConnection = server.getServerConnection();
    try {
        final List<ChannelFuture> endpoints = (List<ChannelFuture>) serverConnection.getClass()
                .getDeclaredField("g").get(serverConnection);
        final List<NetworkManager> networkManagers = (List<NetworkManager>) serverConnection.getClass()
                .getDeclaredField("h").get(serverConnection);

        ChannelFuture channelfuture;

        synchronized (endpoints) {
            channelfuture = new ServerBootstrap().channel(LocalServerChannel.class)
                    .childHandler(new ChannelInitializer<Channel>() {
                        protected void initChannel(Channel channel) throws Exception {

                            NetworkManager networkmanager = new NetworkManager(
                                    EnumProtocolDirection.SERVERBOUND);
                            networkmanager.setPacketListener(
                                    new HandshakeListener(serverConnection.d(), networkmanager));
                            networkManagers.add(networkmanager);

                            channel.pipeline().addLast("timeout", new ReadTimeoutHandler(30));
                            channel.pipeline().addLast("legacy_query", new LegacyPingHandler(serverConnection));
                            channel.pipeline().addLast("splitter", new PacketSplitter());
                            channel.pipeline().addLast("decoder",
                                    new PacketDecoder(EnumProtocolDirection.SERVERBOUND));
                            channel.pipeline().addLast("prepender", new PacketPrepender());
                            channel.pipeline().addLast("encoder",
                                    new PacketEncoder(EnumProtocolDirection.CLIENTBOUND));
                            channel.pipeline().addLast("packet_handler", networkmanager);
                        }
                    }).group(new NioEventLoopGroup(4)).localAddress(LocalAddress.ANY).bind()
                    .syncUninterruptibly();

            endpoints.add(channelfuture);
        }

        LemmingClient client = manager.newLemming().name("TotallyNotABot").address("192.168.0.10", 2344)
                .latency(20).packetLoss(3).throttling(400).create().connect();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:io.cettia.asity.bridge.netty4.AsityServerCodec.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        if (!accept(req)) {
            ctx.fireChannelRead(msg);/*  w ww.  j  a  va2s . c  o m*/
            return;
        }
        if (req.getMethod() == HttpMethod.GET
                && req.headers().contains(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET, true)) {
            // Because WebSocketServerHandshaker requires FullHttpRequest
            FullHttpRequest wsRequest = new DefaultFullHttpRequest(req.getProtocolVersion(), req.getMethod(),
                    req.getUri());
            wsRequest.headers().set(req.headers());
            wsReqMap.put(ctx.channel(), wsRequest);
            // Set timeout to avoid memory leak
            ctx.pipeline().addFirst(new ReadTimeoutHandler(5));
        } else {
            NettyServerHttpExchange http = new NettyServerHttpExchange(ctx, req);
            httpMap.put(ctx.channel(), http);
            httpActions.fire(http);
        }
    } else if (msg instanceof HttpContent) {
        FullHttpRequest wsReq = wsReqMap.get(ctx.channel());
        if (wsReq != null) {
            wsReq.content().writeBytes(((HttpContent) msg).content());
            if (msg instanceof LastHttpContent) {
                wsReqMap.remove(ctx.channel());
                // Cancel timeout
                ctx.pipeline().remove(ReadTimeoutHandler.class);
                WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory(
                        getWebSocketLocation(ctx.pipeline(), wsReq), null, true);
                WebSocketServerHandshaker handshaker = factory.newHandshaker(wsReq);
                if (handshaker == null) {
                    WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
                } else {
                    handshaker.handshake(ctx.channel(), wsReq);
                    NettyServerWebSocket ws = new NettyServerWebSocket(ctx, wsReq, handshaker);
                    wsMap.put(ctx.channel(), ws);
                    wsActions.fire(ws);
                }
            }
        } else {
            NettyServerHttpExchange http = httpMap.get(ctx.channel());
            if (http != null) {
                http.handleChunk((HttpContent) msg);
            }
        }
    } else if (msg instanceof WebSocketFrame) {
        NettyServerWebSocket ws = wsMap.get(ctx.channel());
        if (ws != null) {
            ws.handleFrame((WebSocketFrame) msg);
        }
    }
}

From source file:io.tetrapod.core.flashpolicy.FlashPolicyServer.java

License:Apache License

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast("timeout", new ReadTimeoutHandler(5));
    pipeline.addLast("decoder", new FlashPolicyServerDecoder());
    pipeline.addLast("handler", new FlashPolicyServerHandler());
}

From source file:me.ferrybig.javacoding.teamspeakconnector.internal.TeamspeakConnectionInitizer.java

License:Open Source License

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast(new DelimiterBasedFrameDecoder(Short.MAX_VALUE, LINES));
    pipeline.addLast(DECODER);//from   ww w  . j a v a  2  s. c  o  m
    pipeline.addLast(ENCODER);
    pipeline.addLast(new ReadTimeoutHandler(timeout));
    pipeline.addLast(new HandshakeListener(prom));

    pipeline.addLast(PACKET_DECODER);
    pipeline.addLast(new ComplexPacketDecoder());
    pipeline.addLast(PACKET_ENCODER);

    pipeline.addLast(new LoggingHandler(LogLevel.INFO));

    pipeline.addLast(new PacketRateLimitingHandler());
}