Example usage for io.netty.channel ChannelOption SO_TIMEOUT

List of usage examples for io.netty.channel ChannelOption SO_TIMEOUT

Introduction

In this page you can find the example usage for io.netty.channel ChannelOption SO_TIMEOUT.

Prototype

ChannelOption SO_TIMEOUT

To view the source code for io.netty.channel ChannelOption SO_TIMEOUT.

Click Source Link

Usage

From source file:TestTCP.java

License:Open Source License

public static void main(String... args) throws Throwable {
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int width = (int) screenSize.getWidth();
    int height = (int) screenSize.getHeight();
    JFrame ventanica = new JFrame("HTTP test");
    ventanica.setBounds((width - 500) / 2, (height - 400) / 2, 500, 400);

    resultado = new JTextPane();
    resultado.setEditable(true);/*  ww  w .j  a  v a2 s . c  o m*/
    resultado.setContentType("text/txt");
    resultado.setEditable(false);

    final JTextField direccion = new JTextField();
    JScrollPane scrollPane = new JScrollPane(resultado);
    final JLabel bytesSentLabel = new JLabel("Bytes Sent: 0B");
    final JLabel bytesReceivedLabel = new JLabel("Bytes Received: 0B");
    final JLabel timeSpent = new JLabel("Time: 0ms");
    timeSpent.setHorizontalAlignment(SwingConstants.CENTER);
    JPanel bottomPanel = new JPanel(new BorderLayout(1, 3));
    bottomPanel.add(bytesSentLabel, BorderLayout.WEST);
    bottomPanel.add(timeSpent, BorderLayout.CENTER);
    bottomPanel.add(bytesReceivedLabel, BorderLayout.EAST);

    ventanica.setLayout(new BorderLayout(3, 1));
    ventanica.add(direccion, BorderLayout.NORTH);
    ventanica.add(scrollPane, BorderLayout.CENTER);
    ventanica.add(bottomPanel, BorderLayout.SOUTH);

    ventanica.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    ventanica.setVisible(true);

    final IOService service = new IOService();

    direccion.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final TCPSocket socket = new TCPSocket(service);
            resultado.setText("");
            bytesSentLabel.setText("Bytes Sent: 0B");
            bytesReceivedLabel.setText("Bytes Received: 0B");
            timeSpent.setText("Time: 0ms");
            direccion.setEnabled(false);

            String addr = direccion.getText();
            String host, path = "/";
            int puerto = 80;
            try {
                URL url = new URL((addr.startsWith("http://") ? "" : "http://") + addr);
                host = url.getHost();
                path = url.getPath().isEmpty() ? "/" : url.getPath();
                puerto = url.getPort() == -1 ? url.getDefaultPort() : url.getPort();
            } catch (MalformedURLException e1) {
                String as[] = addr.split(":");
                host = as[0];
                if (as.length > 1) {
                    puerto = Integer.parseInt(as[1]);
                }
            }
            final String request = "GET " + path + " HTTP/1.1\r\n" + "Accept-Charset: utf-8\r\n"
                    + "User-Agent: JavaNettyMelchor629\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n"
                    + "\r\n";

            Callback<Future<Void>> l = new Callback<Future<Void>>() {
                @Override
                public void call(Future<Void> arg) {
                    final long start = System.currentTimeMillis();
                    final ByteBuf b = ByteBufAllocator.DEFAULT.buffer(16 * 1024).retain();
                    socket.onClose().whenDone(new Callback<Future<Void>>() {
                        @Override
                        public void call(Future<Void> arg) {
                            direccion.setEnabled(true);

                            long spent = System.currentTimeMillis() - start;
                            timeSpent.setText(String.format("Time spent: %dms", spent));
                            b.release();
                        }
                    });
                    socket.setOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
                    socket.setOption(ChannelOption.SO_TIMEOUT, 5000);

                    socket.sendAsync(ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT, request))
                            .whenDone(new Callback<Future<Void>>() {
                                @Override
                                public void call(Future<Void> arg) {
                                    bytesSentLabel.setText("Bytes Sent: " + socket.sendBytes() + "B");
                                    final Callback<Future<Long>> cbk = new Callback<Future<Long>>() {
                                        @Override
                                        public void call(Future<Long> arg) {
                                            bytesReceivedLabel
                                                    .setText("Bytes Received: " + socket.receivedBytes() + "B");
                                            if (!arg.isSuccessful())
                                                return;

                                            byte b1[] = new byte[(int) (long) arg.getValueNow()];
                                            b.getBytes(0, b1);
                                            resultado.setText(resultado.getText()
                                                    + new String(b1).replace("\r", "\\r").replace("\n", "\\n\n")
                                                    + "");
                                            b.setIndex(0, 0);
                                            socket.receiveAsync(b).whenDone(this);
                                        }
                                    };
                                    socket.receiveAsync(b).whenDone(cbk);
                                }
                            });
                }
            };

            try {
                socket.connectAsync(host, puerto, new OracleJREServerProvider()).whenDone(l);
            } catch (Throwable ignore) {
            }
        }
    });

    ventanica.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            service.cancel();
        }
    });
}

From source file:TestSSL.java

License:Open Source License

public static void main(String[] args) {
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int width = (int) screenSize.getWidth();
    int height = (int) screenSize.getHeight();
    JFrame ventanica = new JFrame("HTTPS test");
    ventanica.setBounds((width - 500) / 2, (height - 400) / 2, 500, 400);

    resultado = new JTextPane();
    resultado.setEditable(true);// w w  w.j a  v  a  2s  .  c o  m
    resultado.setContentType("text/txt");
    resultado.setEditable(false);

    final JTextField direccion = new JTextField();
    JScrollPane scrollPane = new JScrollPane(resultado);
    final JLabel bytesSentLabel = new JLabel("Bytes Sent: 0B");
    final JLabel bytesReceivedLabel = new JLabel("Bytes Received: 0B");
    final JLabel timeSpent = new JLabel("Time: 0ms");
    timeSpent.setHorizontalAlignment(SwingConstants.CENTER);
    JPanel bottomPanel = new JPanel(new BorderLayout(1, 3));
    bottomPanel.add(bytesSentLabel, BorderLayout.WEST);
    bottomPanel.add(timeSpent, BorderLayout.CENTER);
    bottomPanel.add(bytesReceivedLabel, BorderLayout.EAST);

    ventanica.setLayout(new BorderLayout(3, 1));
    ventanica.add(direccion, BorderLayout.NORTH);
    ventanica.add(scrollPane, BorderLayout.CENTER);
    ventanica.add(bottomPanel, BorderLayout.SOUTH);

    ventanica.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    ventanica.setVisible(true);

    final IOService service = new IOService();

    direccion.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final SSLSocket socket = new SSLSocket(service);
            resultado.setText("");
            bytesSentLabel.setText("Bytes Sent: 0B");
            bytesReceivedLabel.setText("Bytes Received: 0B");
            timeSpent.setText("Time: 0ms");
            direccion.setEnabled(false);

            String addr = direccion.getText();
            String host, path = "/";
            int puerto = 80;
            try {
                URL url = new URL((addr.startsWith("https://") ? "" : "https://") + addr);
                host = url.getHost();
                path = url.getPath().isEmpty() ? "/" : url.getPath();
                puerto = url.getPort() == -1 ? url.getDefaultPort() : url.getPort();
            } catch (MalformedURLException e1) {
                String as[] = addr.split(":");
                host = as[0];
                if (as.length > 1) {
                    puerto = Integer.parseInt(as[1]);
                }
            }
            final String request = "GET " + path + " HTTP/1.1\r\n" + "Accept-Charset: utf-8\r\n"
                    + "User-Agent: JavaNettyMelchor629\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n"
                    + "\r\n";

            Callback<Future<Void>> l = new Callback<Future<Void>>() {
                @Override
                public void call(Future<Void> arg) {
                    final long start = System.currentTimeMillis();
                    final ByteBuf b = ByteBufAllocator.DEFAULT.buffer(16 * 1024).retain();
                    socket.onClose().whenDone(new Callback<Future<Void>>() {
                        @Override
                        public void call(Future<Void> arg) {
                            direccion.setEnabled(true);

                            long spent = System.currentTimeMillis() - start;
                            timeSpent.setText(String.format("Time spent: %dms", spent));
                            b.release();
                        }
                    });
                    socket.setOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
                    socket.setOption(ChannelOption.SO_TIMEOUT, 5000);

                    socket.sendAsync(ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT, request))
                            .whenDone(new Callback<Future<Void>>() {
                                @Override
                                public void call(Future<Void> arg) {
                                    bytesSentLabel.setText("Bytes Sent: " + socket.sendBytes() + "B");
                                    final Callback<Future<Long>> cbk = new Callback<Future<Long>>() {
                                        @Override
                                        public void call(Future<Long> arg) {
                                            bytesReceivedLabel
                                                    .setText("Bytes Received: " + socket.receivedBytes() + "B");
                                            if (!arg.isSuccessful())
                                                return;

                                            byte b1[] = new byte[(int) (long) arg.getValueNow()];
                                            b.getBytes(0, b1);
                                            resultado.setText(resultado.getText()
                                                    + new String(b1).replace("\r", "\\r").replace("\n", "\\n\n")
                                                    + "");
                                            b.setIndex(0, 0);
                                            socket.receiveAsync(b).whenDone(this);
                                        }
                                    };
                                    socket.receiveAsync(b).whenDone(cbk);
                                }
                            });
                }
            };

            try {
                socket.connectAsync(host, puerto, new OracleJREServerProvider()).whenDone(l);
            } catch (Throwable ignore) {
            }
        }
    });

    ventanica.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            service.cancel();
        }
    });
}

From source file:com.github.milenkovicm.kafka.connection.AbstractKafkaBroker.java

License:Apache License

public AbstractKafkaBroker(String hostname, int port, String topicName, EventLoopGroup workerGroup,
        ProducerProperties properties) {
    this.hostname = hostname;
    this.port = port;
    this.topicName = topicName;
    this.workerGroup = workerGroup;
    this.properties = properties;

    this.bootstrap = new Bootstrap();
    this.bootstrap.group(this.workerGroup);
    this.bootstrap.channel(NioSocketChannel.class);
    this.bootstrap.option(ChannelOption.TCP_NODELAY, true);
    this.bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK,
            properties.get(ProducerProperties.NETTY_HIGH_WATERMARK));
    this.bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK,
            properties.get(ProducerProperties.NETTY_LOW_WATERMARK));

    this.bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    if (properties.get(ProducerProperties.SO_TIMEOUT) > 0) {
        this.bootstrap.option(ChannelOption.SO_TIMEOUT, 0);
    }//from ww  w  .j a va  2 s .c om

    if (properties.get(ProducerProperties.SO_RCVBUF) > 0) {
        this.bootstrap.option(ChannelOption.SO_RCVBUF, 0);
    }

    if (properties.get(ProducerProperties.SO_SNDBUF) > 0) {
        this.bootstrap.option(ChannelOption.SO_SNDBUF, 0);
    }

    this.bootstrap.handler(pipeline());
}

From source file:com.heliosapm.streams.onramp.OnRampBoot.java

License:Apache License

/**
 * Creates a new OnRampBoot//  w ww  .  j a v a  2 s  .com
 * @param appConfig  The application configuration
 */
public OnRampBoot(final Properties appConfig) {
    final String jmxmpUri = ConfigurationHelper.getSystemThenEnvProperty("jmx.jmxmp.uri",
            "jmxmp://0.0.0.0:1893", appConfig);
    JMXHelper.fireUpJMXMPServer(jmxmpUri);
    MessageForwarder.initialize(appConfig);
    port = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.port", 8091, appConfig);
    bindInterface = ConfigurationHelper.getSystemThenEnvProperty("onramp.network.bind", "0.0.0.0", appConfig);
    bindSocket = new InetSocketAddress(bindInterface, port);
    workerThreads = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.worker_threads", CORES * 2,
            appConfig);
    connectTimeout = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.sotimeout", 0, appConfig);
    backlog = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.backlog", 3072, appConfig);
    writeSpins = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.writespins", 16, appConfig);
    recvBuffer = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.recbuffer", 43690, appConfig);
    sendBuffer = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.sendbuffer", 8192, appConfig);
    disableEpoll = ConfigurationHelper.getBooleanSystemThenEnvProperty("onramp.network.epoll.disable", false,
            appConfig);
    async = ConfigurationHelper.getBooleanSystemThenEnvProperty("onramp.network.async_io", true, appConfig);
    tcpNoDelay = ConfigurationHelper.getBooleanSystemThenEnvProperty("onramp.network.tcp_no_delay", true,
            appConfig);
    keepAlive = ConfigurationHelper.getBooleanSystemThenEnvProperty("onramp.network.keep_alive", true,
            appConfig);
    reuseAddress = ConfigurationHelper.getBooleanSystemThenEnvProperty("onramp.network.reuse_address", true,
            appConfig);
    tcpPipelineFactory = new PipelineFactory(appConfig);
    udpPipelineFactory = new UDPPipelineFactory();
    tcpServerBootstrap.handler(new LoggingHandler(getClass(), LogLevel.INFO));
    tcpServerBootstrap.childHandler(tcpPipelineFactory);
    // Set the child options
    tcpServerBootstrap.childOption(ChannelOption.ALLOCATOR, BufferManager.getInstance().getAllocator());
    tcpServerBootstrap.childOption(ChannelOption.TCP_NODELAY, tcpNoDelay);
    tcpServerBootstrap.childOption(ChannelOption.SO_KEEPALIVE, keepAlive);
    tcpServerBootstrap.childOption(ChannelOption.SO_RCVBUF, recvBuffer);
    tcpServerBootstrap.childOption(ChannelOption.SO_SNDBUF, sendBuffer);
    tcpServerBootstrap.childOption(ChannelOption.WRITE_SPIN_COUNT, writeSpins);
    // Set the server options
    tcpServerBootstrap.option(ChannelOption.SO_BACKLOG, backlog);
    tcpServerBootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress);
    tcpServerBootstrap.option(ChannelOption.SO_RCVBUF, recvBuffer);
    tcpServerBootstrap.option(ChannelOption.SO_TIMEOUT, connectTimeout);

    final StringBuilder tcpUri = new StringBuilder("tcp");
    final StringBuilder udpUri = new StringBuilder("udp");
    if (IS_LINUX && !disableEpoll) {
        bossExecutorThreadFactory = new ExecutorThreadFactory("EpollServerBoss", true);
        bossGroup = new EpollEventLoopGroup(1, (ThreadFactory) bossExecutorThreadFactory);
        workerExecutorThreadFactory = new ExecutorThreadFactory("EpollServerWorker", true);
        workerGroup = new EpollEventLoopGroup(workerThreads, (ThreadFactory) workerExecutorThreadFactory);
        tcpChannelType = EpollServerSocketChannel.class;
        udpChannelType = EpollDatagramChannel.class;
        tcpUri.append("epoll");
        udpUri.append("epoll");
    } else {
        bossExecutorThreadFactory = new ExecutorThreadFactory("NioServerBoss", true);
        bossGroup = new NioEventLoopGroup(1, bossExecutorThreadFactory);
        workerExecutorThreadFactory = new ExecutorThreadFactory("NioServerWorker", true);
        workerGroup = new NioEventLoopGroup(workerThreads, workerExecutorThreadFactory);
        tcpChannelType = NioServerSocketChannel.class;
        udpChannelType = NioDatagramChannel.class;
        tcpUri.append("nio");
        udpUri.append("nio");
    }

    tcpUri.append("://").append(bindInterface).append(":").append(port);
    udpUri.append("://").append(bindInterface).append(":").append(port);
    URI u = null;
    try {
        u = new URI(tcpUri.toString());
    } catch (URISyntaxException e) {
        log.warn("Failed TCP server URI const: [{}]. Programmer Error", tcpUri, e);
    }
    tcpServerURI = u;
    try {
        u = new URI(udpUri.toString());
    } catch (URISyntaxException e) {
        log.warn("Failed UDP server URI const: [{}]. Programmer Error", udpUri, e);
    }
    udpServerURI = u;

    log.info(">>>>> Starting OnRamp TCP Listener on [{}]...", tcpServerURI);
    log.info(">>>>> Starting OnRamp UDP Listener on [{}]...", udpServerURI);
    final ChannelFuture cf = tcpServerBootstrap.channel(tcpChannelType).group(bossGroup, workerGroup)
            .bind(bindSocket).awaitUninterruptibly()
            .addListener(new GenericFutureListener<Future<? super Void>>() {
                public void operationComplete(final Future<? super Void> f) throws Exception {
                    log.info("<<<<< OnRamp TCP Listener on [{}] Started", tcpServerURI);
                };
            }).awaitUninterruptibly();
    final ChannelFuture ucf = udpBootstrap.channel(udpChannelType).group(workerGroup)
            .option(ChannelOption.SO_BROADCAST, true).handler(new UDPPipelineFactory()).bind(bindSocket)
            .awaitUninterruptibly().addListener(new GenericFutureListener<Future<? super Void>>() {
                public void operationComplete(final Future<? super Void> f) throws Exception {
                    log.info("<<<<< OnRamp UDP Listener on [{}] Started", udpServerURI);
                };
            }).awaitUninterruptibly();

    tcpServerChannel = cf.channel();
    udpServerChannel = ucf.channel();
    tcpCloseFuture = tcpServerChannel.closeFuture();
    udpCloseFuture = udpServerChannel.closeFuture();
    Runtime.getRuntime().addShutdownHook(shutdownHook);

}

From source file:com.openddal.server.NettyServer.java

License:Apache License

private ServerBootstrap configServer() {
    bossGroup = new NioEventLoopGroup(args.bossThreads, new DefaultThreadFactory("NettyBossGroup", true));
    workerGroup = new NioEventLoopGroup(args.workerThreads, new DefaultThreadFactory("NettyWorkerGroup", true));
    userExecutor = createUserThreadExecutor();
    Authenticator authenticator = createAuthenticator();
    ProcessorFactory processorFactory = createProcessorFactory();
    RequestFactory requestFactory = createRequestFactory();
    ResponseFactory responseFactory = createResponseFactory();
    final ProtocolHandler protocolHandler = new ProtocolHandler(authenticator, processorFactory, requestFactory,
            responseFactory, userExecutor);

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true);

    if (args.socketTimeoutMills > 0) {
        b.childOption(ChannelOption.SO_TIMEOUT, args.socketTimeoutMills);
    }/*  w ww.java2  s  .c o  m*/

    if (args.recvBuff > 0) {
        b.childOption(ChannelOption.SO_RCVBUF, args.recvBuff);
    }

    if (args.sendBuff > 0) {
        b.childOption(ChannelOption.SO_SNDBUF, args.sendBuff);
    }

    b.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(createProtocolDecoder(), /* createProtocolEncoder(), */ protocolHandler);
        }
    });

    return b;
}

From source file:darks.grid.network.GridMessageServer.java

License:Apache License

@Override
public boolean initialize() {
    try {// www  .  j av  a 2 s  .co  m
        NetworkConfig config = GridRuntime.config().getNetworkConfig();
        int bossNum = Runtime.getRuntime().availableProcessors() * config.getServerBossThreadDelta();
        int workerNum = config.getServerWorkerThreadNumber();
        bossGroup = new NioEventLoopGroup(bossNum);
        workerGroup = new NioEventLoopGroup(workerNum);
        super.initialize();
        bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, config.isTcpNodelay())
                .option(ChannelOption.SO_KEEPALIVE, config.isTcpKeepAlive())
                .option(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true))
                //            .option(ChannelOption.SO_TIMEOUT, config.getRecvTimeout())
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout())
                .option(ChannelOption.SO_REUSEADDR, config.isTcpReuseAddr())
                //            .option(ChannelOption.SO_BACKLOG, config.getTcpBacklog())
                .option(ChannelOption.SO_SNDBUF, config.getTcpSendBufferSize())
                .option(ChannelOption.SO_RCVBUF, config.getTcpRecvBufferSize())
                .childOption(ChannelOption.TCP_NODELAY, config.isTcpNodelay())
                .childOption(ChannelOption.SO_KEEPALIVE, config.isTcpKeepAlive())
                .childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true))
                .childOption(ChannelOption.SO_TIMEOUT, config.getRecvTimeout())
                .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout())
                .childOption(ChannelOption.SO_REUSEADDR, config.isTcpReuseAddr())
                .childOption(ChannelOption.SO_BACKLOG, config.getTcpBacklog())
                .childOption(ChannelOption.SO_SNDBUF, config.getTcpSendBufferSize())
                .childOption(ChannelOption.SO_RCVBUF, config.getTcpRecvBufferSize());
        bootstrap.childHandler(newChannelHandler());
        return true;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return false;
    }
}

From source file:de.jackwhite20.comix.Comix.java

License:Open Source License

public void start() {
    System.setProperty("java.net.preferIPv4Stack", "true");

    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.DISABLED);

    AnsiConsole.systemInstall();//from  w w w . j  a  v  a2s  .c o m

    LogManager.getLogManager().reset();

    logger = new ComixLogger(consoleReader);

    logger.log(Level.INFO, "Comix", "------ Comix v.0.1 ------");

    loadConfig();

    logger.log(Level.INFO, "Load-Balancer", (targets.size() > 0) ? "Targets:" : "No Target Servers found!");
    targets.forEach(t -> logger.log(Level.INFO, "Load-Balancer",
            t.getName() + " - " + t.getHost() + ":" + t.getPort()));

    logger.log(Level.INFO, "Commands", "Registering commands...");

    registerCommands();

    logger.log(Level.INFO, "Comix", "Starting Comix on " + balancerHost + ":" + balancerPort + "...");

    balancingStrategy = new RoundRobinBalancingStrategy(targets);

    new Timer("CheckTargets").scheduleAtFixedRate(new CheckTargets(balancingStrategy), 0,
            TimeUnit.SECONDS.toMillis(comixConfig.getCheckTime()));

    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup(comixConfig.getThreads());

    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_BACKLOG, comixConfig.getBacklog())
                .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.AUTO_READ, false).childOption(ChannelOption.SO_TIMEOUT, 4000)
                .childHandler(new ComixChannelInitializer());

        ChannelFuture f = bootstrap.bind(comixConfig.getPort()).sync();

        reload();

        logger.log(Level.INFO, "Comix", "Comix is started!");

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

        running = false;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        shutdown();
    }
}

From source file:de.jackwhite20.comix.handler.UpstreamHandler.java

License:Open Source License

public void connectDownstream(ByteBuf initPacket) {
    InetSocketAddress address = (InetSocketAddress) upstreamChannel.remoteAddress();
    TargetData target = this.strategy.selectTarget(address.getHostName(), address.getPort());

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(upstreamChannel.eventLoop()).channel(upstreamChannel.getClass())
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.AUTO_READ, false)
            .option(ChannelOption.SO_TIMEOUT, 5000).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000)
            .handler(downstreamHandler = new DownstreamHandler(client, upstreamChannel));

    ChannelFuture f = bootstrap.connect(target.getHost(), target.getPort());
    downstreamChannel = f.channel();// www. jav a  2 s.  c  o m

    initialPackets.add(initPacket);

    f.addListener((future) -> {
        if (future.isSuccess()) {
            downstreamConnected = true;

            for (ByteBuf packet : initialPackets) {
                downstreamChannel.writeAndFlush(packet);
            }

            Comix.getLogger().log(Level.INFO, "Proxy",
                    "[" + client.getName() + "] <-> [Comix] <-> [" + target.getName() + "] tunneled");
        } else {
            upstreamChannel.close();
        }
    });
}

From source file:io.grpc.netty.UtilsTest.java

License:Apache License

private static InternalChannelz.SocketOptions setAndValidateGeneric(Channel channel) {
    channel.config().setOption(ChannelOption.SO_LINGER, 3);
    // only applicable for OIO channels:
    channel.config().setOption(ChannelOption.SO_TIMEOUT, 250);
    // Test some arbitrarily chosen options with a non numeric values
    channel.config().setOption(ChannelOption.SO_KEEPALIVE, true);
    WriteBufferWaterMark writeBufWaterMark = new WriteBufferWaterMark(10, 20);
    channel.config().setOption(ChannelOption.WRITE_BUFFER_WATER_MARK, writeBufWaterMark);

    InternalChannelz.SocketOptions socketOptions = Utils.getSocketOptions(channel);
    assertEquals(3, (int) socketOptions.lingerSeconds);
    assertEquals("true", socketOptions.others.get("SO_KEEPALIVE"));
    assertEquals(writeBufWaterMark.toString(),
            socketOptions.others.get(ChannelOption.WRITE_BUFFER_WATER_MARK.toString()));
    return socketOptions;
}

From source file:io.mycat.netty.NettyServer.java

License:Apache License

private ServerBootstrap configServer() {
    bossGroup = new NioEventLoopGroup(args.bossThreads, new DefaultThreadFactory("NettyBossGroup", true));
    workerGroup = new NioEventLoopGroup(args.workerThreads, new DefaultThreadFactory("NettyWorkerGroup", true));
    userExecutor = createUserThreadExecutor();

    final ProtocolHandler handshakeHandler = newHandshakeHandler(userExecutor);
    final ProtocolHandler protocolHandler = newProtocolHandler(userExecutor);

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true);

    if (args.socketTimeoutMills > 0) {
        b.childOption(ChannelOption.SO_TIMEOUT, args.socketTimeoutMills);
    }//  www . ja v a  2s  .co m

    if (args.recvBuff > 0) {
        b.childOption(ChannelOption.SO_RCVBUF, args.recvBuff);
    }

    if (args.sendBuff > 0) {
        b.childOption(ChannelOption.SO_SNDBUF, args.sendBuff);
    }

    b.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(createProtocolDecoder(), /* createProtocolEncoder(), */ handshakeHandler,
                    protocolHandler);
        }
    });

    return b;
}