當前位置: 首頁>>代碼示例>>Java>>正文


Java NioDatagramChannel類代碼示例

本文整理匯總了Java中io.netty.channel.socket.nio.NioDatagramChannel的典型用法代碼示例。如果您正苦於以下問題:Java NioDatagramChannel類的具體用法?Java NioDatagramChannel怎麽用?Java NioDatagramChannel使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


NioDatagramChannel類屬於io.netty.channel.socket.nio包,在下文中一共展示了NioDatagramChannel類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: UDPServerSocket

import io.netty.channel.socket.nio.NioDatagramChannel; //導入依賴的package包/類
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);
    }
}
 
開發者ID:Rsplwe,項目名稱:Nukkit-Java9,代碼行數:17,代碼來源:UDPServerSocket.java

示例2: create

import io.netty.channel.socket.nio.NioDatagramChannel; //導入依賴的package包/類
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();
}
 
開發者ID:talentchain,項目名稱:talchain,代碼行數:20,代碼來源:UdpTest.java

示例3: UDPServerSocket

import io.netty.channel.socket.nio.NioDatagramChannel; //導入依賴的package包/類
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);
    }
}
 
開發者ID:JupiterDevelopmentTeam,項目名稱:Jupiter,代碼行數:17,代碼來源:UDPServerSocket.java

示例4: run

import io.netty.channel.socket.nio.NioDatagramChannel; //導入依賴的package包/類
@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();
    }
}
 
開發者ID:jeikerxiao,項目名稱:SpringBootStudy,代碼行數:21,代碼來源:UdpServer.java

示例5: run

import io.netty.channel.socket.nio.NioDatagramChannel; //導入依賴的package包/類
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();
	}
}
 
開發者ID:rafradek,項目名稱:Mods,代碼行數:21,代碼來源:TF2UdpServer.java

示例6: TF2UdpClient

import io.netty.channel.socket.nio.NioDatagramChannel; //導入依賴的package包/類
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));*/
}
 
開發者ID:rafradek,項目名稱:Mods,代碼行數:20,代碼來源:TF2UdpClient.java

示例7: main

import io.netty.channel.socket.nio.NioDatagramChannel; //導入依賴的package包/類
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();
	}
	
}
 
開發者ID:hdcuican,項目名稱:java_learn,代碼行數:22,代碼來源:ChineseProverbClient.java

示例8: ConnectionService

import io.netty.channel.socket.nio.NioDatagramChannel; //導入依賴的package包/類
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();
    }
}
 
開發者ID:WarpOrganization,項目名稱:warp,代碼行數:22,代碼來源:ConnectionService.java

示例9: initialize

import io.netty.channel.socket.nio.NioDatagramChannel; //導入依賴的package包/類
/**
 * 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();
}
 
開發者ID:GoMint,項目名稱:jRakNet,代碼行數:40,代碼來源:ClientSocket.java

示例10: UDPServerSocket

import io.netty.channel.socket.nio.NioDatagramChannel; //導入依賴的package包/類
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);
    }
}
 
開發者ID:BukkitPE,項目名稱:BukkitPE,代碼行數:19,代碼來源:UDPServerSocket.java

示例11: UDPServerSocket

import io.netty.channel.socket.nio.NioDatagramChannel; //導入依賴的package包/類
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);
    }
}
 
開發者ID:PrismarineMC,項目名稱:MagmaBlock,代碼行數:17,代碼來源:UDPServerSocket.java

示例12: McpeOverRakNetNetworkListener

import io.netty.channel.socket.nio.NioDatagramChannel; //導入依賴的package包/類
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);
    }
}
 
開發者ID:voxelwind,項目名稱:voxelwind,代碼行數:22,代碼來源:McpeOverRakNetNetworkListener.java

示例13: init

import io.netty.channel.socket.nio.NioDatagramChannel; //導入依賴的package包/類
@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);
}
 
開發者ID:SecureSmartHome,項目名稱:SecureSmartHome,代碼行數:19,代碼來源:UDPDiscoveryServer.java

示例14: newBootstrapUDP

import io.netty.channel.socket.nio.NioDatagramChannel; //導入依賴的package包/類
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);
}
 
開發者ID:duchien85,項目名稱:netty-cookbook,代碼行數:8,代碼來源:BootstrapTemplate.java

示例15: run

import io.netty.channel.socket.nio.NioDatagramChannel; //導入依賴的package包/類
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();
}
   }
 
開發者ID:changyuefeng,項目名稱:netty-book,代碼行數:21,代碼來源:ChineseProverbClient.java


注:本文中的io.netty.channel.socket.nio.NioDatagramChannel類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。