Netty默认支持TCP、UDP、SCTP、UDT这几种网络协议,前面的一些示例都是说的TCP协议的SocketChannel,如UDP就不需要建立连接,也叫作无连接的协议,不需要调用connect()方法,只需要调用bind()方法。

    1. // 创建BootStrap
    2. Bootstrap b = new Bootstrap();
    3. b.group(group) // 指定EventLoopGroup以处理客户端事件,需要适用于NIO的实现
    4. .channel(NioDatagramChannel.class) // 适用于NIO传输的Channel类型
    5. .remoteAddress(new InetSocketAddress(host, port)) // 设置服务器的InetSockerAddress
    6. .handler(new ChannelInitializer<SocketChannel>() { // 在创建Channel时,向ChannelPipeline中添加一个EchoClientHandler实例
    7. @Override
    8. protected void initChannel(SocketChannel ch) throws Exception {
    9. ch.pipeline().addLast(new EchoClientHandler());
    10. }
    11. });
    12. // 调用bind()方法,因为该协议的无连接的。
    13. ChannelFuture f = b.bind(new InetSocketAddress(0));
    14. // 阻塞,直到Channel关闭
    15. f.channel().closeFuture().sync();