Example usage for io.netty.channel.oio OioEventLoopGroup OioEventLoopGroup

List of usage examples for io.netty.channel.oio OioEventLoopGroup OioEventLoopGroup

Introduction

In this page you can find the example usage for io.netty.channel.oio OioEventLoopGroup OioEventLoopGroup.

Prototype

public OioEventLoopGroup(int maxChannels) 

Source Link

Document

Create a new OioEventLoopGroup .

Usage

From source file:com.stremebase.examples.todomvc.Todo.java

License:Apache License

public static void main(String[] args) throws Exception {
    css = new String(Files.readAllBytes(Paths.get(System.getProperty("user.dir"), "Web", "index.css")));
    favicon = Files.readAllBytes(Paths.get(System.getProperty("user.dir"), "Web", "favicon.ico"));

    Table.setDefaultDb(new DB("user.dir"));
    data = new Data(itemTableId, "ITEMTABLE");

    @SuppressWarnings("unchecked")
    Router<Integer> router = new Router<Integer>().GET("/", GET).GET("/filter/:filtertype", FILTER)

            .POST("/", POST).POST("/delete", DELETE).POST("/clearcompleted", DELETECOMPLETED)
            .POST("/toggle-status", TOGGLESTATUS)

            .GET(":something/index.css", CSS).GET("/index.css", CSS).GET("/favicon.ico", ICON)
            .notFound(NOTFOUND);/*  w  ww. j  a  va  2  s. co  m*/
    System.out.println(router);

    OioEventLoopGroup bossGroup = new OioEventLoopGroup(1);
    SingleThreadEventLoop workerGroup = new ThreadPerChannelEventLoop(bossGroup);

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).childOption(ChannelOption.TCP_NODELAY, java.lang.Boolean.TRUE)
                .childOption(ChannelOption.SO_KEEPALIVE, java.lang.Boolean.TRUE)
                .childOption(ChannelOption.SO_REUSEADDR, java.lang.Boolean.TRUE)
                .channel(OioServerSocketChannel.class).childHandler(new HttpRouterServerInitializer(router));

        Channel ch = b.bind(PORT).sync().channel();
        System.out.println("Server started: http://127.0.0.1:" + PORT + '/');

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

From source file:com.whizzosoftware.hobson.api.plugin.channel.AbstractChannelObjectPlugin.java

License:Open Source License

/**
 * Creates the appropriate EventLoopGroup based on whether the remote address is a network address or serial port.
 *
 * @return an EventLoopGroup/* w ww. j  av  a 2s.  c om*/
 */
private EventLoopGroup createEventLoopGroup() {
    // create new event loop group
    if (isNetworkAddress()) {
        return new NioEventLoopGroup(1);
    } else if (isSerialAddress()) {
        return new OioEventLoopGroup(1);
    } else {
        throw new HobsonRuntimeException("Remote address is neither network nor serial");
    }
}

From source file:dorkbox.network.Broadcast.java

License:Apache License

static List<BroadcastResponse> discoverHosts0(Logger logger, int udpPort, int discoverTimeoutMillis,
        boolean fetchAllServers) throws IOException {
    // fetch a buffer that contains the serialized object.
    ByteBuf buffer = Unpooled.buffer(1);
    buffer.writeByte(MagicBytes.broadcastID);

    List<BroadcastResponse> servers = new ArrayList<BroadcastResponse>();

    Enumeration<NetworkInterface> networkInterfaces;
    try {//from   w  ww.java  2 s .c o m
        networkInterfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        if (logger != null) {
            logger.error("Host discovery failed.", e);
        }
        throw new IOException("Host discovery failed. No interfaces found.");
    }

    scan: for (NetworkInterface networkInterface : Collections.list(networkInterfaces)) {
        for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
            InetAddress address = interfaceAddress.getAddress();
            InetAddress broadcast = interfaceAddress.getBroadcast();

            // don't use IPv6!
            if (address instanceof Inet6Address) {
                if (logger != null) {
                    if (logger.isInfoEnabled()) {
                        logger.info("Not using IPv6 address: {}", address);
                    }
                }
                continue;
            }

            try {
                if (logger != null) {
                    if (logger.isInfoEnabled()) {
                        logger.info("Searching for host on [{}:{}]", address.getHostAddress(), udpPort);
                    }
                }

                EventLoopGroup group;
                Class<? extends Channel> channelClass;

                if (OS.isAndroid()) {
                    // android ONLY supports OIO (not NIO)
                    group = new OioEventLoopGroup(1);
                    channelClass = OioDatagramChannel.class;
                } else {
                    group = new NioEventLoopGroup(1);
                    channelClass = NioDatagramChannel.class;
                }

                Bootstrap udpBootstrap = new Bootstrap().group(group).channel(channelClass)
                        .option(ChannelOption.SO_BROADCAST, true).handler(new ClientDiscoverHostInitializer())
                        .localAddress(new InetSocketAddress(address, 0)); // pick random address. Not listen for broadcast.

                // we don't care about RECEIVING a broadcast packet, we are only SENDING one.
                ChannelFuture future;
                try {
                    future = udpBootstrap.bind();
                    future.await();
                } catch (InterruptedException e) {
                    if (logger != null) {
                        logger.error("Could not bind to random UDP address on the server.", e.getCause());
                    }
                    throw new IOException("Could not bind to random UDP address on the server.");
                }

                if (!future.isSuccess()) {
                    if (logger != null) {
                        logger.error("Could not bind to random UDP address on the server.", future.cause());
                    }
                    throw new IOException("Could not bind to random UDP address on the server.");
                }

                Channel channel1 = future.channel();

                if (broadcast != null) {
                    // try the "defined" broadcast first if we have it (not always!)
                    channel1.writeAndFlush(
                            new DatagramPacket(buffer, new InetSocketAddress(broadcast, udpPort)));

                    // response is received.  If the channel is not closed within 5 seconds, move to the next one.
                    if (!channel1.closeFuture().awaitUninterruptibly(discoverTimeoutMillis)) {
                        if (logger != null) {
                            if (logger.isInfoEnabled()) {
                                logger.info("Host discovery timed out.");
                            }
                        }
                    } else {
                        BroadcastResponse broadcastResponse = channel1.attr(ClientDiscoverHostHandler.STATE)
                                .get();
                        servers.add(broadcastResponse);
                    }

                    // keep going if we want to fetch all servers. Break if we found one.
                    if (!(fetchAllServers || servers.isEmpty())) {
                        channel1.close().await();
                        group.shutdownGracefully().await();
                        break scan;
                    }
                }

                // continue with "common" broadcast addresses.
                // Java 1.5 doesn't support getting the subnet mask, so try them until we find one.

                byte[] ip = address.getAddress();
                for (int octect = 3; octect >= 0; octect--) {
                    ip[octect] = -1; // 255.255.255.0

                    // don't error out on one particular octect
                    try {
                        InetAddress byAddress = InetAddress.getByAddress(ip);
                        channel1.writeAndFlush(
                                new DatagramPacket(buffer, new InetSocketAddress(byAddress, udpPort)));

                        // response is received.  If the channel is not closed within 5 seconds, move to the next one.
                        if (!channel1.closeFuture().awaitUninterruptibly(discoverTimeoutMillis)) {
                            if (logger != null) {
                                if (logger.isInfoEnabled()) {
                                    logger.info("Host discovery timed out.");
                                }
                            }
                        } else {
                            BroadcastResponse broadcastResponse = channel1.attr(ClientDiscoverHostHandler.STATE)
                                    .get();
                            servers.add(broadcastResponse);

                            if (!fetchAllServers) {
                                break;
                            }
                        }
                    } catch (Exception ignored) {
                    }
                }

                channel1.close().sync();
                group.shutdownGracefully(0, discoverTimeoutMillis, TimeUnit.MILLISECONDS);

            } catch (Exception ignored) {
            }

            // keep going if we want to fetch all servers. Break if we found one.
            if (!(fetchAllServers || servers.isEmpty())) {
                break scan;
            }
        }
    }

    if (logger != null && logger.isInfoEnabled() && !servers.isEmpty()) {
        StringBuilder stringBuilder = new StringBuilder(256);

        if (fetchAllServers) {
            stringBuilder.append("Discovered servers: (").append(servers.size()).append(")");

            for (BroadcastResponse server : servers) {
                stringBuilder.append("/n").append(server.remoteAddress).append(":");

                if (server.tcpPort > 0) {
                    stringBuilder.append(server.tcpPort);

                    if (server.udpPort > 0) {
                        stringBuilder.append(":");
                    }
                }
                if (server.udpPort > 0) {
                    stringBuilder.append(udpPort);
                }
            }
            logger.info(stringBuilder.toString());
        } else {
            BroadcastResponse server = servers.get(0);
            stringBuilder.append(server.remoteAddress).append(":");

            if (server.tcpPort > 0) {
                stringBuilder.append(server.tcpPort);

                if (server.udpPort > 0) {
                    stringBuilder.append(":");
                }
            }
            if (server.udpPort > 0) {
                stringBuilder.append(udpPort);
            }

            logger.info("Discovered server [{}]", stringBuilder.toString());
        }
    }

    return servers;
}

From source file:org.openremote.agent.protocol.AbstractSerialMessageProcessor.java

License:Open Source License

@SuppressWarnings("deprecation")
@Override
protected io.netty.channel.EventLoopGroup getWorkerGroup() {
    return new OioEventLoopGroup(1);
}