Java Code Examples for io.netty.channel.socket.nio.NioDatagramChannel

The following are top voted examples for showing how to use io.netty.channel.socket.nio.NioDatagramChannel. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Nukkit-Java9   File: UDPServerSocket.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 2
Project: talchain   File: UdpTest.java   View source code 6 votes vote down vote up
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();
}
 
Example 3
Project: Jupiter   File: UDPServerSocket.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 4
Project: Jenisys3   File: UDPServerSocket.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 5
Project: SpringBootStudy   File: UdpServer.java   View source code 6 votes vote down vote up
@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();
    }
}
 
Example 6
Project: AppCoins-ethereumj   File: UdpTest.java   View source code 6 votes vote down vote up
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();
}
 
Example 7
Project: Mods   File: TF2UdpServer.java   View source code 6 votes vote down vote up
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();
	}
}
 
Example 8
Project: Mods   File: TF2UdpClient.java   View source code 6 votes vote down vote up
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));*/
}
 
Example 9
Project: CoreX   File: UDPServerSocket.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 10
Project: java_learn   File: ChineseProverbClient.java   View source code 6 votes vote down vote up
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();
	}
	
}
 
Example 11
Project: warp   File: ConnectionService.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 12
Project: jRakNet   File: ClientSocket.java   View source code 6 votes vote down vote up
/**
 * Initializes this socket and binds its internal udp socket to a free port.
 * If the socket is already initialized any invocation of this method will
 * result in an IllegalStateException.
 *
 * @throws SocketException Thrown in case the socket could not be initialized
 */
public void initialize() throws SocketException {
    if ( this.isInitialized() ) {
        throw new IllegalStateException( "Cannot re-initialized ClientSocket" );
    }

    this.udpSocket = new Bootstrap();
    this.udpSocket.group( Epoll.isAvailable() ? new EpollEventLoopGroup() : new NioEventLoopGroup() );
    this.udpSocket.channel( Epoll.isAvailable() ? EpollDatagramChannel.class : NioDatagramChannel.class );
    this.udpSocket.handler( new ChannelInboundHandlerAdapter() {
        @Override
        public void channelRead( ChannelHandlerContext ctx, Object msg ) throws Exception {
            io.netty.channel.socket.DatagramPacket packet = (io.netty.channel.socket.DatagramPacket) msg;
            PacketBuffer content = new PacketBuffer( packet.content() );
            InetSocketAddress sender = packet.sender();

            if ( !receiveDatagram( sender, content ) ) {
                // Push datagram to update queue:
                handleDatagram( sender, content, System.currentTimeMillis() );
            }
        }
    } );

    try {
        this.channel = this.udpSocket.bind( ThreadLocalRandom.current().nextInt( 45000, 65000 ) ).sync().channel();
    } catch ( InterruptedException e ) {
        SocketException exception = new SocketException( "Could not bind to socket" );
        exception.initCause( e );
        throw exception;
    }

    this.afterInitialize();
}
 
Example 13
Project: Nemisys   File: UDPServerSocket.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 14
Project: BukkitPE   File: UDPServerSocket.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 15
Project: NukkitGT   File: UDPServerSocket.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 16
Project: Apollo-OLD   File: UDPServerSocket.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 17
Project: MagmaBlock   File: UDPServerSocket.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 18
Project: voxelwind   File: McpeOverRakNetNetworkListener.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 19
Project: SecureSmartHome   File: UDPDiscoveryServer.java   View source code 6 votes vote down vote up
@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);
}
 
Example 20
Project: netty-cookbook   File: BootstrapTemplate.java   View source code 6 votes vote down vote up
public static ChannelFuture newBootstrapUDP(EventLoopGroup loopGroup, SimpleChannelInboundHandler<DatagramPacket> handler, int port){
	return new Bootstrap().group(loopGroup)
			.channel(NioDatagramChannel.class)
			.option(ChannelOption.SO_BROADCAST, true)
			.handler(handler)
			.bind(port);
}
 
Example 21
Project: netty-book   File: ChineseProverbClient.java   View source code 6 votes vote down vote up
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();
}
   }
 
Example 22
Project: jfastnet   File: KryoNettyPeer.java   View source code 6 votes vote down vote up
@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;
}
 
Example 23
Project: Nukkit   File: UDPServerSocket.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 24
Project: udp-multiplexer-proxy   File: RtpPartyA.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 25
Project: DistributedLog4j   File: UDPListener.java   View source code 6 votes vote down vote up
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();
	}
 
Example 26
Project: DistributedLog4j   File: UDPAppender.java   View source code 6 votes vote down vote up
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");
		}
	}
 
Example 27
Project: hope-tactical-equipment   File: ChineseProverbClient.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 28
Project: netty4study   File: QuoteOfTheMomentClient.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 29
Project: kume   File: MulticastServerHandler.java   View source code 6 votes vote down vote up
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();
}
 
Example 30
Project: jtftp   File: TftpServer.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 31
Project: distributeTemplate   File: BootstrapFactory.java   View source code 6 votes vote down vote up
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!");
    }
}
 
Example 32
Project: distributeTemplate   File: ServerUDPBootstrapFactory.java   View source code 6 votes vote down vote up
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!");
    }
}
 
Example 33
Project: netty-netty-5.0.0.Alpha1   File: QuoteOfTheMomentClient.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 34
Project: whale   File: IotNettyService.java   View source code 6 votes vote down vote up
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);
	}
}
 
Example 35
Project: sipstack   File: UAS.java   View source code 6 votes vote down vote up
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();
}
 
Example 36
Project: tomp2p_5   File: ChannelServer.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 37
Project: logstash-gelf   File: WildFlyHandlerIntegrationTests.java   View source code 6 votes vote down vote up
@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();
}
 
Example 38
Project: jts-tanks   File: GameServer.java   View source code 6 votes vote down vote up
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);
}
 
Example 39
Project: sbrw-freeroam-srv   File: NettyUdpServer.java   View source code 5 votes vote down vote up
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;
}
 
Example 40
Project: rskj   File: UDPServer.java   View source code 5 votes vote down vote up
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);
                }
            });
}