Java 类io.netty.channel.socket.nio.NioDatagramChannel 实例源码

项目:Nukkit-Java9    文件:UDPServerSocket.java   
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("Perhaps a server is already running on that port?");
        System.exit(1);
    }
}
项目:talchain    文件:UdpTest.java   
public Channel create(String bindAddr, int port) throws InterruptedException {
    NioEventLoopGroup group = new NioEventLoopGroup(1);

    Bootstrap b = new Bootstrap();
    b.group(group)
        .channel(NioDatagramChannel.class)
        .handler(new ChannelInitializer<NioDatagramChannel>() {
            @Override
            public void initChannel(NioDatagramChannel ch)
                    throws Exception {
                ch.pipeline().addLast(new PacketDecoder());
                SimpleMessageHandler messageHandler = new SimpleMessageHandler(ch, nodeManager);
                nodeManager.setMessageSender(messageHandler);
                ch.pipeline().addLast(messageHandler);
            }
        });

    return b.bind(bindAddr, port).sync().channel();
}
项目:Jupiter    文件:UDPServerSocket.java   
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical(FastAppender.get(interfaz, ":", port, " 上でサーバーを開けませんでした。"));
        this.logger.critical("同じポートで複数のサーバーを一度に開いていませんか?");
        System.exit(1);
    }
}
项目:Jenisys3    文件:UDPServerSocket.java   
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("Perhaps a server is already running on that port?");
        System.exit(1);
    }
}
项目:SpringBootStudy    文件:UdpServer.java   
@Async("myTaskAsyncPool")
public void run(int udpReceivePort) {

    EventLoopGroup group = new NioEventLoopGroup();
    logger.info("Server start!  Udp Receive msg Port:" + udpReceivePort);

    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new UdpServerHandler());   // 设置服务端接收消息的 Handler (保存消息到 mysql 和 redis 中)

        b.bind(udpReceivePort).sync().channel().closeFuture().await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        group.shutdownGracefully();
    }
}
项目:AppCoins-ethereumj    文件:UdpTest.java   
public Channel create(String bindAddr, int port) throws InterruptedException {
    NioEventLoopGroup group = new NioEventLoopGroup(1);

    Bootstrap b = new Bootstrap();
    b.group(group)
        .channel(NioDatagramChannel.class)
        .handler(new ChannelInitializer<NioDatagramChannel>() {
            @Override
            public void initChannel(NioDatagramChannel ch)
                    throws Exception {
                ch.pipeline().addLast(new PacketDecoder());
                SimpleMessageHandler messageHandler = new SimpleMessageHandler(ch, nodeManager);
                nodeManager.setMessageSender(messageHandler);
                ch.pipeline().addLast(messageHandler);
            }
        });

    return b.bind(bindAddr, port).sync().channel();
}
项目:Mods    文件:TF2UdpServer.java   
public void run() {
    try {
        Bootstrap boot = new Bootstrap();
        boot.group(group)
         .channel(NioDatagramChannel.class)
         .handler(new ChannelInitializer<DatagramChannel>() {

            @Override
            protected void initChannel(DatagramChannel ch) throws Exception {
                channel = ch;
                ch.pipeline().addLast(new UdpChannelHandlerServer(TF2UdpServer.this));
            }

         });
        boot.bind(port).sync().channel().closeFuture();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
项目:Mods    文件:TF2UdpClient.java   
public TF2UdpClient(InetSocketAddress address) throws Exception {
    group = new NioEventLoopGroup();
    this.address = address;
    EntityPlayerSP player = Minecraft.getMinecraft().player;
    Bootstrap boot = new Bootstrap();
    boot.group(group).channel(NioDatagramChannel.class).handler(new UdpChannelHandlerClient());

    channel = boot.bind(0).sync().channel();

    channel.connect(address);

    /*PacketBuffer buffer = new PacketBuffer(Unpooled.buffer());
    buffer.writeShort(playerId);
    buffer.writeShort(0);
    buffer.writeByte(0);
    buffer.writeLong(System.currentTimeMillis());

    channel.writeAndFlush(new DatagramPacket(buffer, address));*/
}
项目:CoreX    文件:UDPServerSocket.java   
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("Perhaps a server is already running on that port?");
        System.exit(1);
    }
}
项目:java_learn    文件:ChineseProverbClient.java   
public static void main(String[] args) throws Exception {
    EventLoopGroup loopGroup = new NioEventLoopGroup();
    try{
        Bootstrap b = new Bootstrap();
        b.group(loopGroup).channel(NioDatagramChannel.class)
        .option(ChannelOption.SO_BROADCAST, true)
        .handler(new ChannelProverbClientHandler());
        Channel ch = b.bind(0).sync().channel();
        //向网段内所有的机器广播UDP消息
        ch.writeAndFlush(
                new DatagramPacket(Unpooled.copiedBuffer("谚语字典查询?", CharsetUtil.UTF_8),
                new InetSocketAddress("255.255.255.255", port))).sync();
        //客户端等待15s接受服务端的应答消息,然后退出释放资源
        if(!ch.closeFuture().await(15000)){
            System.out.println("查询超时");
        }
    }finally{
        loopGroup.shutdownGracefully();
    }

}
项目:warp    文件:ConnectionService.java   
public ConnectionService(SerializedSceneHolder sceneHolder,
                         ClientRemoteEventQueue eventQueue,
                         ComponentRegistry componentRegistry) {

    try {
        Bootstrap b = new Bootstrap();
        ServerConnectionHandler connectionHandler = new ServerConnectionHandler(
                sceneHolder,
                this,
                eventQueue,
                new EventReceiver(componentRegistry));
        b.group(group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(connectionHandler);

        channel = b.bind(0).sync().channel();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
项目:Nemisys    文件:UDPServerSocket.java   
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("Perhaps a server is already running on that port?");
        System.exit(1);
    }
}
项目:BukkitPE    文件:UDPServerSocket.java   
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (InterruptedException e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("-------------------------------------------------");
        this.logger.critical("There may be another server running on that port!");
        this.logger.critical("--------------------------------------------------");
        System.exit(1);
    }
}
项目:NukkitGT    文件:UDPServerSocket.java   
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("Perhaps a server is already running on that port?");
        System.exit(1);
    }
}
项目:Apollo-OLD    文件:UDPServerSocket.java   
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("Perhaps a server is already running on that port?");
        System.exit(1);
    }
}
项目:MagmaBlock    文件:UDPServerSocket.java   
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (InterruptedException e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("Perhaps a server is already running on that port?");
        System.exit(1);
    }
}
项目:voxelwind    文件:McpeOverRakNetNetworkListener.java   
public McpeOverRakNetNetworkListener(VoxelwindServer voxelwindServer, String host, int port, boolean useSoReuseport) {
    this.server = voxelwindServer;
    this.address = new InetSocketAddress(host, port);
    this.useSoReuseport = useSoReuseport;
    if (Epoll.isAvailable()) {
        bootstrap = new Bootstrap()
                .channel(EpollDatagramChannel.class)
                .group(new EpollEventLoopGroup(0, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("Voxelwind MCPE Listener - #%d").build()))
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .handler(this);
        if (useSoReuseport) {
            bootstrap.option(EpollChannelOption.SO_REUSEPORT, true);
        }
    } else {
        bootstrap = new Bootstrap()
                .channel(NioDatagramChannel.class)
                .group(new NioEventLoopGroup(0, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("Voxelwind MCPE Listener - #%d").build()))
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .handler(this);
    }
}
项目:SecureSmartHome    文件:UDPDiscoveryServer.java   
@Override
public void init(Container container) {
    super.init(container);

    // Acquire lock
    final WifiManager wifi = (WifiManager) requireComponent(ContainerService.KEY_CONTEXT)
            .getSystemService(Context.WIFI_SERVICE);
    multicastLock = wifi.createMulticastLock(getClass().getSimpleName());
    multicastLock.acquire();

    // Setup UDP Channel
    Bootstrap b = new Bootstrap()
            .channel(NioDatagramChannel.class)
            .group(requireComponent(ExecutionServiceComponent.KEY))
            .handler(new RequestHandler())
            .option(ChannelOption.SO_BROADCAST, true);
    channel = b.bind(CoreConstants.NettyConstants.DISCOVERY_SERVER_PORT);
}
项目:netty-book    文件:ChineseProverbClient.java   
public void run(int port) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioDatagramChannel.class)
        .option(ChannelOption.SO_BROADCAST, true)
        .handler(new ChineseProverbClientHandler());
    Channel ch = b.bind(0).sync().channel();
    // 向网段内的所有机器广播UDP消息
    ch.writeAndFlush(
        new DatagramPacket(Unpooled.copiedBuffer("谚语字典查询?",
            CharsetUtil.UTF_8), new InetSocketAddress(
            "255.255.255.255", port))).sync();
    if (!ch.closeFuture().await(15000)) {
    System.out.println("查询超时!");
    }
} finally {
    group.shutdownGracefully();
}
   }
项目:jfastnet    文件:KryoNettyPeer.java   
@Override
public boolean start() {
    group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .option(ChannelOption.SO_SNDBUF, config.socketSendBufferSize)
                .option(ChannelOption.SO_RCVBUF, config.socketReceiveBufferSize)
                .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(config.receiveBufferAllocator))
                .handler(channelHandler != null ? channelHandler : new UdpHandler());

        channel = b.bind(config.bindPort).sync().channel();

    } catch (Exception e) {
        log.error("Couldn't start server.", e);
        return false;
    }
    return true;
}
项目:Nukkit    文件:UDPServerSocket.java   
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("Perhaps a server is already running on that port?");
        System.exit(1);
    }
}
项目:udp-multiplexer-proxy    文件:RtpPartyA.java   
public static void main(String[] args) {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new RtpPartyAHandler());

        ch = b.bind(36001).sync().channel();

        ch.writeAndFlush(new DatagramPacket(
                Unpooled.copiedBuffer(rtpDataByeArray),
                new InetSocketAddress("127.0.0.1", PORT))).sync();

        if (!ch.closeFuture().await(5000)) {
            Assert.fail("Rtp communication timeout");
        } else {

        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        group.shutdownGracefully();
    }
}
项目:DistributedLog4j    文件:UDPListener.java   
public void activateOptions() throws InterruptedException {

        Bootstrap b = new Bootstrap();
        b.group(group)
            .channel(NioDatagramChannel.class)
            .handler(new Log4jHandler());
        b.option(ChannelOption.SO_REUSEADDR, true);
        b.option(ChannelOption.IP_MULTICAST_IF, MulticastSettings.getIface());
        b.option(ChannelOption.TCP_NODELAY, true);

        InetSocketAddress addr = new InetSocketAddress(MulticastSettings.getAddressToBind(), port);

        b.localAddress(port).remoteAddress(addr);
        ch = (DatagramChannel) b.bind().sync().channel();

        ch.joinGroup(multicastAddress, MulticastSettings.getIface()).sync();
    }
项目:DistributedLog4j    文件:UDPAppender.java   
public void activateOptions()  {

        Bootstrap b = new Bootstrap();

        b.group(group)
            .channel(NioDatagramChannel.class);

        b.handler(new Log4jAppenderHandler(port));

        b.option(ChannelOption.IP_MULTICAST_IF, MulticastSettings.getIface());
        b.option(ChannelOption.SO_REUSEADDR, true);
        b.option(ChannelOption.TCP_NODELAY, true);

        InetSocketAddress addr = new InetSocketAddress(MulticastSettings.getAddressToBind(), port);
        b.localAddress(addr);

        try {
            ch = b.bind().sync().channel();
        } catch (InterruptedException e) {
            System.err.println("upd appender error open socket");
        }
    }
项目:hope-tactical-equipment    文件:ChineseProverbClient.java   
public void run(int port) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChineseProverbClientHandler());
        Channel ch = b.bind(0).sync().channel();
        // 向网段内的所有机器广播UDP消息
        ch.writeAndFlush(
                new DatagramPacket(Unpooled.copiedBuffer("谚语字典查询?",
                        CharsetUtil.UTF_8), new InetSocketAddress(
                        "255.255.255.255", port))).sync();
        if (!ch.closeFuture().await(15000)) {
            System.out.println("查询超时!");
        }
    } finally {
        group.shutdownGracefully();
    }
}
项目:netty4study    文件:QuoteOfTheMomentClient.java   
public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(NioDatagramChannel.class)
         .option(ChannelOption.SO_BROADCAST, true)
         .handler(new QuoteOfTheMomentClientHandler());

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

        // Broadcast the QOTM request to port 8080.
        ch.writeAndFlush(new DatagramPacket(
                Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8),
                new InetSocketAddress("255.255.255.255", port))).sync();

        // QuoteOfTheMomentClientHandler will close the DatagramChannel when a
        // response is received.  If the channel is not closed within 5 seconds,
        // print an error message and quit.
        if (!ch.closeFuture().await(5000)) {
            System.err.println("QOTM request timed out.");
        }
    } finally {
        group.shutdownGracefully();
    }
}
项目:kume    文件:MulticastServerHandler.java   
public MulticastServerHandler(Cluster cluster, InetSocketAddress address) throws InterruptedException {
    this.address = address;

    handler = new Bootstrap()
            .channelFactory(() -> new NioDatagramChannel(InternetProtocolFamily.IPv4))
            .localAddress(address)
            .group(new NioEventLoopGroup())
            .option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.IP_MULTICAST_IF, multicastInterface)
            .option(ChannelOption.AUTO_READ, false)
            .handler(new ChannelInitializer<NioDatagramChannel>() {
                @Override
                public void initChannel(NioDatagramChannel ch) throws Exception {
                    ch.pipeline().addLast(new MulticastChannelAdapter(cluster));
                }
            });
    localMember = cluster.getLocalMember();
}
项目:jtftp    文件:TftpServer.java   
public void run() throws Exception {
    // Configure the server.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioDatagramChannel.class)
                .handler(new ChannelInitializer<DatagramChannel>() {
                    @Override
                    public void initChannel(DatagramChannel ch) throws Exception {
                        ch.pipeline().addLast(
                                new LoggingHandler(LogLevel.INFO),
                                new TftpServerHandler());
                    }
                });

        b.bind(port).sync().channel().closeFuture().await();
    } finally {
        group.shutdownGracefully();
    }
}
项目:distributeTemplate    文件:BootstrapFactory.java   
public static Bootstrap createUDPBootstrap(final ChannelType channelType) throws UnsupportedOperationException {
    Bootstrap bootstrap = new Bootstrap();

    switch (channelType) {
        case NIO:

            bootstrap.group(new NioEventLoopGroup());
            bootstrap.channel(NioDatagramChannel.class);
            return bootstrap;

        case OIO:

            bootstrap.group(new OioEventLoopGroup());
            bootstrap.channel(OioDatagramChannel.class);
            return bootstrap;

        default:
            throw new UnsupportedOperationException("Failed to create Bootstrap,  " + channelType + " not supported!");
    }
}
项目:distributeTemplate    文件:ServerUDPBootstrapFactory.java   
public static Bootstrap createServerBootstrap(final ChannelType channelType) throws UnsupportedOperationException {

    Bootstrap serverBootstrap = new Bootstrap();

    switch (channelType) {
        case NIO:
            serverBootstrap.group(new NioEventLoopGroup(Runtime.getRuntime().availableProcessors()));
            serverBootstrap.channel(NioDatagramChannel.class);
           // serverBootstrap.localAddress(new InetSocketAddress(port))
           // .handler(packetHandler);

            return serverBootstrap;

        case OIO:
             serverBootstrap.group(new OioEventLoopGroup(Runtime.getRuntime().availableProcessors()));
             serverBootstrap.channel(OioDatagramChannel.class);


            return serverBootstrap;

        default:
            throw new UnsupportedOperationException("Failed to create ServerBootstrap,  " + channelType + " not supported!");
    }
}
项目:netty-netty-5.0.0.Alpha1    文件:QuoteOfTheMomentClient.java   
public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(NioDatagramChannel.class)
         .option(ChannelOption.SO_BROADCAST, true)
         .handler(new QuoteOfTheMomentClientHandler());

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

        // Broadcast the QOTM request to port 8080.
        ch.writeAndFlush(new DatagramPacket(
                Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8),
                new InetSocketAddress("255.255.255.255", port))).sync();

        // QuoteOfTheMomentClientHandler will close the DatagramChannel when a
        // response is received.  If the channel is not closed within 5 seconds,
        // print an error message and quit.
        if (!ch.closeFuture().await(5000)) {
            System.err.println("QOTM request timed out.");
        }
    } finally {
        group.shutdownGracefully();
    }
}
项目:whale    文件:IotNettyService.java   
public void init() throws InterruptedException {
    if (tcpPort == 0 && udpPort == 0) {
        log.info("tcpPort=0 and udpPort=0, socket proctol disable");
        return;
    }
    bossGroup = new NioEventLoopGroup(2);
    workerGroup = new NioEventLoopGroup();
    udpWorkGroup = new NioEventLoopGroup();
    if (tcpPort > 0) {
        tcpBoot = new ServerBootstrap();
        tcpBoot.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(iotNettyTcpServerInitializer);
        tcpcf = tcpBoot.bind(tcpPort);
    }
    if (udpPort > 0) {
        udpBoot = new Bootstrap();
        udpBoot.group(udpWorkGroup)
            .channel(NioDatagramChannel.class)
            .option(ChannelOption.SO_BROADCAST, true)
            .handler(iotNettyUdpHandler);
        udpcf = udpBoot.bind(udpPort);
    }
}
项目:sipstack    文件:UAS.java   
public static void main(final String[] args) throws Exception {
    final UAS uas = new UAS();
    final EventLoopGroup udpGroup = new NioEventLoopGroup();

    final Bootstrap b = new Bootstrap();
    b.group(udpGroup)
    .channel(NioDatagramChannel.class)
    .handler(new ChannelInitializer<DatagramChannel>() {
        @Override
        protected void initChannel(final DatagramChannel ch) throws Exception {
            final ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("decoder", new SipMessageDatagramDecoder());
            pipeline.addLast("encoder", new SipMessageEncoder());
            pipeline.addLast("handler", uas);
        }
    });

    final InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 5060);
    b.bind(socketAddress).sync().channel().closeFuture().await();
}
项目:tomp2p_5    文件:ChannelServer.java   
/**
 * Start to listen on a UPD port.
 * 
 * @param listenAddresses
 *            The address to listen to
 * @param config
 *            Can create handlers to be attached to this port
 * @return True if startup was successful
 */
boolean startupUDP(final InetSocketAddress listenAddresses, final ChannelServerConficuration config) {
    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioDatagramChannel.class);
    b.option(ChannelOption.SO_BROADCAST, true);
    b.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(ConnectionBean.UDP_LIMIT));

    b.handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(final Channel ch) throws Exception {
            for (Map.Entry<String, ChannelHandler> entry : handlers(false).entrySet()) {
                ch.pipeline().addLast(entry.getKey(), entry.getValue());
            }
        }
    });

    ChannelFuture future = b.bind(listenAddresses);
    channelUDP = future.channel();
    return handleFuture(future);
}
项目:logstash-gelf    文件:WildFlyHandlerIntegrationTests.java   
@Test
public void testGelfSubmissionToEmbeddedNettyGelfServer() throws Exception {
    NettyLocalServer nettyLocalServer = new NettyLocalServer(NioDatagramChannel.class);
    nettyLocalServer.run();
    String logMessage = "some log event";

    int iterations = 0;
    while (nettyLocalServer.getJsonValues().isEmpty() && iterations < 10) {
        LogManager.getLogger(getClass()).info(logMessage);
        Thread.sleep(100);
        iterations++;
    }

    assertThat(nettyLocalServer.getJsonValues()).isNotEmpty();

    boolean foundSomeLogEvent = false;

    for (Object o : nettyLocalServer.getJsonValues()) {
        if (o.toString().contains(logMessage)) {
            foundSomeLogEvent = true;
        }
    }
    assertThat(foundSomeLogEvent).isTrue();
    nettyLocalServer.close();
}
项目:jts-tanks    文件:GameServer.java   
public static void startNetworkServer() {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.option(ChannelOption.SO_BROADCAST, true);
    bootstrap.channel(NioDatagramChannel.class).handler(new Game2ClientChannelHandler());

    String host = GameServerProperty.getInstance().GAME_CLIENT_HOST;
    int port = GameServerProperty.getInstance().GAME_CLIENT_PORT;
    if (host.equals("*")) {
        bootstrap.localAddress(port);
    } else {
        bootstrap.localAddress(host, port);
    }

    NetworkThread clientsNetworkThread = new NetworkThread(bootstrap, true);

    clientsNetworkThread.start();

    log.info("Clients NetworkThread loaded on {}:{}", host, port);
}
项目:sbrw-freeroam-srv    文件:NettyUdpServer.java   
public ChannelFuture start() throws InterruptedException {
    workerGroup = new NioEventLoopGroup();

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup).channel(NioDatagramChannel.class).handler(new ServerChannelInitializer());

    ChannelFuture channelFuture = bootstrap.bind(new InetSocketAddress(port)).syncUninterruptibly();
    channel = channelFuture.channel();

    return channelFuture;
}
项目:rskj    文件:UDPServer.java   
private Bootstrap createBootstrap(EventLoopGroup group) {
    return new Bootstrap().group(group).channel(NioDatagramChannel.class)
            .handler(new ChannelInitializer<NioDatagramChannel>() {
                @Override
                public void initChannel(NioDatagramChannel ch)
                        throws Exception {
                    ch.pipeline().addLast(new PacketDecoder());
                    UDPChannel udpChannel = new UDPChannel(ch, peerExplorer);
                    peerExplorer.setUDPChannel(udpChannel);
                    ch.pipeline().addLast(udpChannel);
                }
            });
}
项目:nearenough    文件:NettyClient.java   
public static void main(String[] args) throws InterruptedException, NoSuchAlgorithmException {
  InetSocketAddress addr = new InetSocketAddress(GOOGLE_SERVER_HOST, GOOGLE_SERVER_PORT);

  System.out.printf("Sending request to %s\n", addr);

  // Below is Netty boilerplate for setting-up an event loop and registering a handler

  NioEventLoopGroup group = new NioEventLoopGroup();
  Bootstrap bootstrap = new Bootstrap()
      .group(group)
      .remoteAddress(addr)
      .channel(NioDatagramChannel.class)
      .handler(new ChannelInitializer<NioDatagramChannel>() {
        @Override
        protected void initChannel(NioDatagramChannel ch) throws Exception {
          ch.pipeline()
              .addLast(new ReadTimeoutHandler(5))
              .addLast(new RequestHandler(addr));
        }
      });

  ChannelFuture connectFuture = bootstrap.connect();
  connectFuture.addListener(fut -> {
    if (!fut.isSuccess()) {
      System.out.println("Connect fail:");
      System.out.println(fut.cause().getMessage());
    }
  });

  connectFuture.channel().closeFuture().sync();
  group.shutdownGracefully();
}
项目:SpringBootStudy    文件:UdpClient.java   
public static void main(String[] args) throws Exception {

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new UdpClientHandler());

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

            String UdpMsg = "this a message form client !";

            logger.info("Client ===> : {}", UdpMsg);

            // Broadcast the QOTM request to port 8880.
            ch.writeAndFlush(new DatagramPacket(
                    Unpooled.copiedBuffer(UdpMsg, CharsetUtil.UTF_8),
                    SocketUtils.socketAddress("localhost", PORT))).sync();

            // UdpClientHandler 接收到服务器响应的消息时,会关闭 DatagramChannel (数据报通道)
            // 如果 DatagramChannel (数据报通道) 没有在 5秒内关闭,那么打印错误日志,并退出
            if (!ch.closeFuture().await(5000)) {
                logger.error("Server response timed out.");
            }
        } finally {
            group.shutdownGracefully();
        }
    }