Java Code Examples for io.netty.util.internal.PlatformDependent#isWindows()

The following examples show how to use io.netty.util.internal.PlatformDependent#isWindows() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DefaultDatagramChannelConfig.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public DatagramChannelConfig setBroadcast(boolean broadcast) {
    try {
        // See: https://github.com/netty/netty/issues/576
        if (broadcast &&
            !javaSocket.getLocalAddress().isAnyLocalAddress() &&
            !PlatformDependent.isWindows() && !PlatformDependent.maybeSuperUser()) {
            // Warn a user about the fact that a non-root user can't receive a
            // broadcast packet on *nix if the socket is bound on non-wildcard address.
            logger.warn(
                    "A non-root user can't receive a broadcast packet if the socket " +
                    "is not bound to a wildcard address; setting the SO_BROADCAST flag " +
                    "anyway as requested on the socket which is bound to " +
                    javaSocket.getLocalSocketAddress() + '.');
        }

        javaSocket.setBroadcast(broadcast);
    } catch (SocketException e) {
        throw new ChannelException(e);
    }
    return this;
}
 
Example 2
Source File: DefaultDatagramChannelConfig.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Override
public DatagramChannelConfig setBroadcast(boolean broadcast) {
    try {
        // See: https://github.com/netty/netty/issues/576
        if (broadcast &&
            !javaSocket.getLocalAddress().isAnyLocalAddress() &&
            !PlatformDependent.isWindows() && !PlatformDependent.isRoot()) {
            // Warn a user about the fact that a non-root user can't receive a
            // broadcast packet on *nix if the socket is bound on non-wildcard address.
            logger.warn(
                    "A non-root user can't receive a broadcast packet if the socket " +
                    "is not bound to a wildcard address; setting the SO_BROADCAST flag " +
                    "anyway as requested on the socket which is bound to " +
                    javaSocket.getLocalSocketAddress() + '.');
        }

        javaSocket.setBroadcast(broadcast);
    } catch (SocketException e) {
        throw new ChannelException(e);
    }
    return this;
}
 
Example 3
Source File: DnsNameResolver.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private InetAddress resolveHostsFileEntry(String hostname) {
    if (hostsFileEntriesResolver == null) {
        return null;
    } else {
        InetAddress address = hostsFileEntriesResolver.address(hostname, resolvedAddressTypes);
        if (address == null && PlatformDependent.isWindows() && LOCALHOST.equalsIgnoreCase(hostname)) {
            // If we tried to resolve localhost we need workaround that windows removed localhost from its
            // hostfile in later versions.
            // See https://github.com/netty/netty/issues/5386
            return LOCALHOST_ADDRESS;
        }
        return address;
    }
}
 
Example 4
Source File: HashedWheelTimer.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * calculate goal nanoTime from startTime and current tick number,
 * then wait until that goal has been reached.从startTime和current tick number计算目标纳时,然后等待目标达到。
 * @return Long.MIN_VALUE if received a shutdown request,
 * current time otherwise (with Long.MIN_VALUE changed by +1)
 */
private long waitForNextTick() {
    long deadline = tickDuration * (tick + 1);

    for (;;) {
        final long currentTime = System.nanoTime() - startTime;
        long sleepTimeMs = (deadline - currentTime + 999999) / 1000000;

        if (sleepTimeMs <= 0) {
            if (currentTime == Long.MIN_VALUE) {
                return -Long.MAX_VALUE;
            } else {
                return currentTime;
            }
        }

        // Check if we run on windows, as if thats the case we will need
        // to round the sleepTime as workaround for a bug that only affect
        // the JVM if it runs on windows.
        //
        // See https://github.com/netty/netty/issues/356
        if (PlatformDependent.isWindows()) {
            sleepTimeMs = sleepTimeMs / 10 * 10;
        }

        try {
            Thread.sleep(sleepTimeMs);
        } catch (InterruptedException ignored) {
            if (WORKER_STATE_UPDATER.get(HashedWheelTimer.this) == WORKER_STATE_SHUTDOWN) {
                return Long.MIN_VALUE;
            }
        }
    }
}
 
Example 5
Source File: HashedWheelTimer.java    From qmq with Apache License 2.0 5 votes vote down vote up
/**
 * calculate goal nanoTime from startTime and current tick number,
 * then wait until that goal has been reached.
 *
 * @return Long.MIN_VALUE if received a shutdown request,
 * current time otherwise (with Long.MIN_VALUE changed by +1)
 */
private long waitForNextTick() {
    long deadline = tickDuration * (tick + 1);

    for (; ; ) {
        final long currentTime = System.nanoTime() - startTime;
        long sleepTimeMs = (deadline - currentTime + 999999) / 1000000;

        if (sleepTimeMs <= 0) {
            if (currentTime == Long.MIN_VALUE) {
                return -Long.MAX_VALUE;
            } else {
                return currentTime;
            }
        }

        // Check if we run on windows, as if thats the case we will need
        // to round the sleepTime as workaround for a bug that only affect
        // the JVM if it runs on windows.
        //
        // See https://github.com/netty/netty/issues/356
        if (PlatformDependent.isWindows()) {
            sleepTimeMs = sleepTimeMs / 10 * 10;
        }

        try {
            Thread.sleep(sleepTimeMs);
        } catch (InterruptedException ignored) {
            if (WORKER_STATE_UPDATER.get(HashedWheelTimer.this) == WORKER_STATE_SHUTDOWN) {
                return Long.MIN_VALUE;
            }
        }
    }
}
 
Example 6
Source File: AbstractChannel.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
public final void bind(final SocketAddress localAddress, final ChannelPromise promise) {
    if (!promise.setUncancellable() || !ensureOpen(promise)) {
        return;
    }

    // See: https://github.com/netty/netty/issues/576
    if (Boolean.TRUE.equals(config().getOption(ChannelOption.SO_BROADCAST)) &&
        localAddress instanceof InetSocketAddress &&
        !((InetSocketAddress) localAddress).getAddress().isAnyLocalAddress() &&
        !PlatformDependent.isWindows() && !PlatformDependent.isRoot()) {
        // Warn a user about the fact that a non-root user can't receive a
        // broadcast packet on *nix if the socket is bound on non-wildcard address.
        logger.warn(
                "A non-root user can't receive a broadcast packet if the socket " +
                "is not bound to a wildcard address; binding to a non-wildcard " +
                "address (" + localAddress + ") anyway as requested.");
    }

    boolean wasActive = isActive();
    try {
        doBind(localAddress);
    } catch (Throwable t) {
        safeSetFailure(promise, t);
        closeIfClosed();
        return;
    }

    if (!wasActive && isActive()) {
        invokeLater(new OneTimeTask() {
            @Override
            public void run() {
                pipeline.fireChannelActive();
            }
        });
    }

    safeSetSuccess(promise);
}
 
Example 7
Source File: HashedWheelTimer.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
/**
 * calculate goal nanoTime from startTime and current tick number,
 * then wait until that goal has been reached.
 * @return Long.MIN_VALUE if received a shutdown request,
 * current time otherwise (with Long.MIN_VALUE changed by +1)
 */
private long waitForNextTick() {
    long deadline = tickDuration * (tick + 1);

    for (;;) {
        final long currentTime = System.nanoTime() - startTime;
        long sleepTimeMs = (deadline - currentTime + 999999) / 1000000;

        if (sleepTimeMs <= 0) {
            if (currentTime == Long.MIN_VALUE) {
                return -Long.MAX_VALUE;
            } else {
                return currentTime;
            }
        }

        // Check if we run on windows, as if thats the case we will need
        // to round the sleepTime as workaround for a bug that only affect
        // the JVM if it runs on windows.
        //
        // See https://github.com/netty/netty/issues/356
        if (PlatformDependent.isWindows()) {
            sleepTimeMs = sleepTimeMs / 10 * 10;
        }

        try {
            Thread.sleep(sleepTimeMs);
        } catch (InterruptedException ignored) {
            if (WORKER_STATE_UPDATER.get(HashedWheelTimer.this) == WORKER_STATE_SHUTDOWN) {
                return Long.MIN_VALUE;
            }
        }
    }
}
 
Example 8
Source File: BGPPeerAcceptorImpl.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
public BGPPeerAcceptorImpl(final IpAddressNoZone bindingAddress, final PortNumber portNumber,
        final BGPDispatcher bgpDispatcher) {
    this.bgpDispatcher = requireNonNull(bgpDispatcher);
    this.address = getAddress(requireNonNull(bindingAddress), requireNonNull(portNumber));
    if (!PlatformDependent.isWindows() && !PlatformDependent.maybeSuperUser()
            && portNumber.getValue().toJava() < PRIVILEGED_PORTS) {
        throw new AccessControlException("Unable to bind port " + portNumber.getValue()
                + " while running as non-root user.");
    }
}
 
Example 9
Source File: Controller.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Starts the BGP controller.
 */
public void start() {
    log.info("Started");
    if (!PlatformDependent.isWindows() && !PlatformDependent.maybeSuperUser()) {
        portNumber = BGP_PRIVILEGED_PORT;
    } else {
        portNumber = BGP_PORT_NUM;
    }
    this.init();
    this.run();
}
 
Example 10
Source File: AbstractChannel.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Override
        public final void bind(final SocketAddress localAddress, final ChannelPromise promise) {
            assertEventLoop();

            if (!promise.setUncancellable() || !ensureOpen(promise)) {
                return;
            }

            // See: https://github.com/netty/netty/issues/576
            if (Boolean.TRUE.equals(config().getOption(ChannelOption.SO_BROADCAST)) &&
                localAddress instanceof InetSocketAddress &&
                !((InetSocketAddress) localAddress).getAddress().isAnyLocalAddress() &&
                !PlatformDependent.isWindows() && !PlatformDependent.maybeSuperUser()) {
                // Warn a user about the fact that a non-root user can't receive a
                // broadcast packet on *nix if the socket is bound on non-wildcard address.
                logger.warn(
                        "A non-root user can't receive a broadcast packet if the socket " +
                        "is not bound to a wildcard address; binding to a non-wildcard " +
                        "address (" + localAddress + ") anyway as requested.");
            }

            boolean wasActive = isActive();
            try {
//                调用java底层bind操作
                doBind(localAddress);
            } catch (Throwable t) {
//                发布bind失败事件
                safeSetFailure(promise, t);
//                channel如果是打开的就关闭
                closeIfClosed();
                return;
            }

            if (!wasActive && isActive()) {
                invokeLater(new Runnable() {
                    @Override
                    public void run() {
//                        触发pipeline的激活事件
                        pipeline.fireChannelActive();
                    }
                });
            }

//            发布bind成功事件
            safeSetSuccess(promise);
        }
 
Example 11
Source File: NettyTest.java    From Lealone-Plugins with Apache License 2.0 4 votes vote down vote up
public static void main2(String[] args) throws Exception {
    NettyNetServerStart.optimizeNetty();

    long t0 = System.currentTimeMillis();
    long t1 = System.currentTimeMillis();
    // 这行执行很慢
    // String[] a = ((SSLSocketFactory) SSLSocketFactory.getDefault()).getDefaultCipherSuites();
    // System.out.println(a.length);
    long t2 = System.currentTimeMillis();
    // System.out.println("getDefaultCipherSuites: " + (t2 - t1) + "ms");

    t1 = System.currentTimeMillis();
    NetworkInterface.getNetworkInterfaces();
    t2 = System.currentTimeMillis();
    System.out.println("1 NetworkInterface.getNetworkInterfaces(): " + (t2 - t1) + "ms");

    t1 = System.currentTimeMillis();
    NetworkInterface.getNetworkInterfaces();
    t2 = System.currentTimeMillis();
    System.out.println("2 NetworkInterface.getNetworkInterfaces(): " + (t2 - t1) + "ms");

    t1 = System.currentTimeMillis();
    PlatformDependent.isWindows();
    t2 = System.currentTimeMillis();
    System.out.println("PlatformDependent init: " + (t2 - t1) + "ms");

    t1 = System.currentTimeMillis();
    // 调用了NetworkInterface.getNetworkInterfaces()导致很慢(近400ms)
    System.out.println(io.netty.util.NetUtil.SOMAXCONN);
    // test();
    t2 = System.currentTimeMillis();
    System.out.println("NetUtil init: " + (t2 - t1) + "ms");

    t1 = System.currentTimeMillis();
    SelectorProvider.provider().openSelector();
    t2 = System.currentTimeMillis();
    System.out.println("1 openSelector: " + (t2 - t1) + "ms");

    t1 = System.currentTimeMillis();
    SelectorProvider.provider().openSelector();
    t2 = System.currentTimeMillis();
    System.out.println("2 openSelector: " + (t2 - t1) + "ms");

    t1 = System.currentTimeMillis();
    NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
    t2 = System.currentTimeMillis();
    System.out.println("1 new NioEventLoopGroup: " + (t2 - t1) + "ms");

    t1 = System.currentTimeMillis();
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    t2 = System.currentTimeMillis();
    System.out.println("2 new NioEventLoopGroup: " + (t2 - t1) + "ms");
    System.out.println("1 total: " + (t2 - t0) + "ms");

    try {
        t1 = System.currentTimeMillis();
        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 Exception {
                        // ChannelPipeline p = ch.pipeline();
                        // p.addLast(new LoggingHandler(LogLevel.INFO));
                        // p.addLast(new EchoServerHandler());
                    }
                });
        t2 = System.currentTimeMillis();
        System.out.println("init ServerBootstrap: " + (t2 - t1) + "ms");

        t1 = System.currentTimeMillis();
        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();
        t2 = System.currentTimeMillis();
        System.out.println("bind ServerBootstrap: " + (t2 - t1) + "ms");
        System.out.println("2 total: " + (t2 - t0) + "ms");
        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}