Netty默认支持TCP、UDP、SCTP、UDT这几种网络协议,前面的一些示例都是说的TCP协议的SocketChannel,如UDP就不需要建立连接,也叫作无连接的协议,不需要调用connect()方法,只需要调用bind()方法。
// 创建BootStrapBootstrap b = new Bootstrap();b.group(group) // 指定EventLoopGroup以处理客户端事件,需要适用于NIO的实现.channel(NioDatagramChannel.class) // 适用于NIO传输的Channel类型.remoteAddress(new InetSocketAddress(host, port)) // 设置服务器的InetSockerAddress.handler(new ChannelInitializer<SocketChannel>() { // 在创建Channel时,向ChannelPipeline中添加一个EchoClientHandler实例@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ch.pipeline().addLast(new EchoClientHandler());}});// 调用bind()方法,因为该协议的无连接的。ChannelFuture f = b.bind(new InetSocketAddress(0));// 阻塞,直到Channel关闭f.channel().closeFuture().sync();
