Example usage for io.netty.channel ChannelOption SO_BACKLOG

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

Introduction

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

Prototype

ChannelOption SO_BACKLOG

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

Click Source Link

Usage

From source file:demo.netty.stickypacket.correct.linebased.TimeServer.java

License:Apache License

public void bind(int port) throws Exception {
    // ??NIO/*from w ww .j a  v  a2  s. com*/
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel arg0) throws Exception {
                        arg0.pipeline().addLast(new LineBasedFrameDecoder(1024));
                        arg0.pipeline().addLast(new StringDecoder());
                        arg0.pipeline().addLast(new TimeServerHandler());
                    }
                });
        // ???
        ChannelFuture f = b.bind(port).sync();

        // ???
        f.channel().closeFuture().sync();
    } finally {
        // ?
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:demo.netty.stickypacket.err.TimeServer.java

License:Apache License

public void bind(int port) throws Exception {
    // ??NIO//from w  w  w  .  ja  v a2s  .c  o  m
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel arg0) throws Exception {
                        arg0.pipeline().addLast(new TimeServerHandler());
                    }

                });
        // ???
        ChannelFuture f = b.bind(port).sync();

        // ???
        f.channel().closeFuture().sync();
    } finally {
        // ?
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:dorkbox.network.Server.java

License:Apache License

/**
 * Convenience method to starts a server with the specified Connection Options
 *//* w  w w . java 2  s .  c  om*/
@SuppressWarnings("AutoBoxing")
public Server(Configuration config) throws SecurityException {
    // watch-out for serialization... it can be NULL incoming. The EndPoint (superclass) sets it, if null, so
    // you have to make sure to use this.serialization
    super(config);

    tcpPort = config.tcpPort;
    udpPort = config.udpPort;

    localChannelName = config.localChannelName;

    if (config.host == null) {
        // we set this to "0.0.0.0" so that it is clear that we are trying to bind to that address.
        hostName = "0.0.0.0";

        // make it clear that this is what we do (configuration wise) so that variable examination is consistent
        config.host = hostName;
    } else {
        hostName = config.host;
    }

    if (localChannelName != null) {
        localBootstrap = new ServerBootstrap();
    } else {
        localBootstrap = null;
    }

    if (tcpPort > 0) {
        tcpBootstrap = new ServerBootstrap();
    } else {
        tcpBootstrap = null;
    }

    if (udpPort > 0) {
        // This is what allows us to have UDP behave "similar" to TCP, in that a session is established based on the port/ip of the
        // remote connection. This allows us to reuse channels and have "state" for a UDP connection that normally wouldn't exist.
        // Additionally, this is what responds to discovery broadcast packets
        udpBootstrap = new SessionBootstrap(tcpPort, udpPort);
    } else {
        udpBootstrap = null;
    }

    String threadName = Server.class.getSimpleName();

    // always use local channels on the server.
    if (localBootstrap != null) {
        localBootstrap
                .group(newEventLoop(LOCAL, 1, threadName + "-JVM-BOSS"), newEventLoop(LOCAL, 1, threadName))
                .channel(LocalServerChannel.class)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .option(ChannelOption.WRITE_BUFFER_WATER_MARK,
                        new WriteBufferWaterMark(WRITE_BUFF_LOW, WRITE_BUFF_HIGH))
                .localAddress(new LocalAddress(localChannelName))
                .childHandler(new RegistrationLocalHandlerServer(threadName, registrationWrapper));
    }

    EventLoopGroup workerEventLoop = null;
    if (tcpBootstrap != null || udpBootstrap != null) {
        workerEventLoop = newEventLoop(config.workerThreadPoolSize, threadName);
    }

    if (tcpBootstrap != null) {
        if (OS.isAndroid()) {
            // android ONLY supports OIO (not NIO)
            tcpBootstrap.channel(OioServerSocketChannel.class);
        } else if (OS.isLinux() && NativeLibrary.isAvailable()) {
            // epoll network stack is MUCH faster (but only on linux)
            tcpBootstrap.channel(EpollServerSocketChannel.class);
        } else if (OS.isMacOsX() && NativeLibrary.isAvailable()) {
            // KQueue network stack is MUCH faster (but only on macosx)
            tcpBootstrap.channel(KQueueServerSocketChannel.class);
        } else {
            tcpBootstrap.channel(NioServerSocketChannel.class);
        }

        // TODO: If we use netty for an HTTP server,
        // Beside the usual ChannelOptions the Native Transport allows to enable TCP_CORK which may come in handy if you implement a HTTP Server.

        tcpBootstrap
                .group(newEventLoop(1, threadName + "-TCP-BOSS"),
                        newEventLoop(1, threadName + "-TCP-REGISTRATION"))
                .option(ChannelOption.SO_BACKLOG, backlogConnectionCount)
                .option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.WRITE_BUFFER_WATER_MARK,
                        new WriteBufferWaterMark(WRITE_BUFF_LOW, WRITE_BUFF_HIGH))

                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new RegistrationRemoteHandlerServerTCP(threadName, registrationWrapper,
                        workerEventLoop));

        // have to check options.host for "0.0.0.0". we don't bind to "0.0.0.0", we bind to "null" to get the "any" address!
        if (hostName.equals("0.0.0.0")) {
            tcpBootstrap.localAddress(tcpPort);
        } else {
            tcpBootstrap.localAddress(hostName, tcpPort);
        }

        // android screws up on this!!
        tcpBootstrap.option(ChannelOption.TCP_NODELAY, !OS.isAndroid()).childOption(ChannelOption.TCP_NODELAY,
                !OS.isAndroid());
    }

    if (udpBootstrap != null) {
        if (OS.isAndroid()) {
            // android ONLY supports OIO (not NIO)
            udpBootstrap.channel(OioDatagramChannel.class);
        } else if (OS.isLinux() && NativeLibrary.isAvailable()) {
            // epoll network stack is MUCH faster (but only on linux)
            udpBootstrap.channel(EpollDatagramChannel.class);
        } else if (OS.isMacOsX() && NativeLibrary.isAvailable()) {
            // KQueue network stack is MUCH faster (but only on macosx)
            udpBootstrap.channel(KQueueDatagramChannel.class);
        } else {
            // windows and linux/mac that are incompatible with the native implementations
            udpBootstrap.channel(NioDatagramChannel.class);
        }

        // Netty4 has a default of 2048 bytes as upper limit for datagram packets, we want this to be whatever we specify
        FixedRecvByteBufAllocator recvByteBufAllocator = new FixedRecvByteBufAllocator(EndPoint.udpMaxSize);

        udpBootstrap
                .group(newEventLoop(1, threadName + "-UDP-BOSS"),
                        newEventLoop(1, threadName + "-UDP-REGISTRATION"))
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator)
                .option(ChannelOption.WRITE_BUFFER_WATER_MARK,
                        new WriteBufferWaterMark(WRITE_BUFF_LOW, WRITE_BUFF_HIGH))

                // a non-root user can't receive a broadcast packet on *nix if the socket is bound on non-wildcard address.
                // TODO: move broadcast to it's own handler, and have UDP server be able to be bound to a specific IP
                // OF NOTE: At the end in my case I decided to bind to .255 broadcast address on Linux systems. (to receive broadcast packets)
                .localAddress(udpPort) // if you bind to a specific interface, Linux will be unable to receive broadcast packets! see: http://developerweb.net/viewtopic.php?id=5722
                .childHandler(new RegistrationRemoteHandlerServerUDP(threadName, registrationWrapper,
                        workerEventLoop));

        // // have to check options.host for null. we don't bind to 0.0.0.0, we bind to "null" to get the "any" address!
        // if (hostName.equals("0.0.0.0")) {
        //     udpBootstrap.localAddress(hostName, tcpPort);
        // }
        // else {
        //     udpBootstrap.localAddress(udpPort);
        // }

        // Enable to READ from MULTICAST data (ie, 192.168.1.0)
        // in order to WRITE: write as normal, just make sure it ends in .255
        // in order to LISTEN:
        //    InetAddress group = InetAddress.getByName("203.0.113.0");
        //    socket.joinGroup(group);
        // THEN once done
        //    socket.leaveGroup(group), close the socket
        // Enable to WRITE to MULTICAST data (ie, 192.168.1.0)
        udpBootstrap.option(ChannelOption.SO_BROADCAST, false).option(ChannelOption.SO_SNDBUF, udpMaxSize);
    }
}

From source file:dream.prehinite.netty.http.server.SampleServer.java

License:Apache License

public void start() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(300);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from   w w  w  .  j a  v a  2  s .  co  m*/
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                //.handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(sampleServerInitializer);

        Channel ch = b.bind(PORT).sync().channel();

        System.err.println("Open your web browser and navigate to " + "http://127.0.0.1:" + PORT + '/');

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:errorcode.DaumStatusServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from  w w  w .  j a va 2 s .co  m
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } else {
        sslCtx = null;
    }

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new DaumStatusServerInitializer(sslCtx));

        Channel ch = b.bind(PORT).sync().channel();

        System.err.println("Open your web browser and navigate to " + (SSL ? "https" : "http") + "://127.0.0.1:"
                + PORT + '/');

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:esens.wp6.ibmJmsBackend.log4http.HttpLogServer.java

License:Apache License

public static void start() throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {// w  w w .jav a  2  s .  c  o  m
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } else {
        sslCtx = null;
    }

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {

        LOGGER.debug("HTTP LOG PORT: " + PORT);
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new HttpLogServerInitializer(sslCtx));

        b.bind(PORT);//.sync().channel();
        //ch.closeFuture().sync();
    } catch (Exception ex) {
        LOGGER.error(ex.getMessage(), ex);
    } finally {
        //bossGroup.shutdownGracefully();
        //workerGroup.shutdownGracefully();
    }
}

From source file:eu.heronnet.module.kad.net.ServerImpl.java

License:Open Source License

@Override
protected void startUp() throws Exception {
    logger.debug("calling startUp for ServerImpl instance={}", this);

    tcpBoostrap = new ServerBootstrap();
    udpbootrap = new Bootstrap();
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();

    tcpBoostrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).localAddress(6565)
            .childHandler(tcpChannelInitializer).option(ChannelOption.SO_BACKLOG, 128)
            .childOption(ChannelOption.SO_KEEPALIVE, true);
    tcpBoostrap.bind().sync();/*from  w  ww .j a  v a2 s . c  om*/

    udpbootrap.group(workerGroup).channel(NioDatagramChannel.class).localAddress(6565)
            .handler(udpChannelInitializer).option(ChannelOption.SO_BROADCAST, true);
    udpbootrap.bind().sync();

}

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

License:Apache License

/**
 * Main of the RealmServer program./*from  w  ww  .j  a va 2 s.c om*/
 *
 * @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.matejkormuth.rpgdavid.starving.remote.RemoteConnectionServer.java

License:Open Source License

private void initializeNetty() {
    // Initialize Netty.
    this.bossGroup = new NioEventLoopGroup(1);
    this.workerGroup = new NioEventLoopGroup(1);

    this.bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ServerChannelInitializer()).option(ChannelOption.TCP_NODELAY, false)
            .option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.TCP_NODELAY, false);
}

From source file:eu.matejkormuth.rpgdavid.starving.remote.RemoteConnetionClient.java

License:Open Source License

private void initializeNetty() {
    this.eventGroup = new NioEventLoopGroup(1);

    this.bootstrap = new Bootstrap();
    this.bootstrap.group(eventGroup).channel(NioSocketChannel.class).handler(new ClientChannelInitializer())
            .option(ChannelOption.TCP_NODELAY, false).option(ChannelOption.SO_BACKLOG, 128);

}