将近快一年时间没有更新Netty的博客。一方面原因是因为项目进度的问题。另外一方面是博主有一段时间去熟悉Unity3D引擎。
本章节主要记录博主自己Netty的UDP协议使用。
1. 构建UDP服务端
首先我们应该清楚UDP协议是一种无连接状态的协议。所以Netty框架区别于一般的有链接协议服务端启动程序(ServerBootstrap)。
Netty开发基于UDP协议的服务端需要使用Bootstrap
1 package dev.tinyz.game; 2 3 import io.netty.bootstrap.Bootstrap; 4 import io.netty.buffer.Unpooled; 5 import io.netty.channel.*; 6 import io.netty.channel.nio.NioEventLoopGroup; 7 import io.netty.channel.socket.DatagramPacket; 8 import io.netty.channel.socket.nio.NioDatagramChannel; 9 import io.netty.handler.codec.MessageToMessageDecoder; 10 11 import java.net.InetSocketAddress; 12 import java.nio.charset.Charset; 13 import java.util.List; 14 15 /** 16 * @author TinyZ on 2015/6/8. 17 */ 18 public class GameMain { 19 20 public static void main(String[] args) throws InterruptedException { 21 22 final NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup(); 23 24 Bootstrap bootstrap = new Bootstrap(); 25 bootstrap.channel(NioDatagramChannel.class); 26 bootstrap.group(nioEventLoopGroup); 27 bootstrap.handler(new ChannelInitializer<NioDatagramChannel>() { 28 29 @Override 30 public void channelActive(ChannelHandlerContext ctx) throws Exception { 31 super.channelActive(ctx); 32 } 33 34 @Override 35 protected void initChannel(NioDatagramChannel ch) throws Exception { 36 ChannelPipeline cp = ch.pipeline(); 37 cp.addLast("framer", new MessageToMessageDecoder<DatagramPacket>() { 38 @Override 39 protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception { 40 out.add(msg.content().toString(Charset.forName("UTF-8"))); 41 } 42 }).addLast("handler", new UdpHandler()); 43 } 44 }); 45 // 监听端口 46 ChannelFuture sync = bootstrap.bind(9009).sync(); 47 Channel udpChannel = sync.channel(); 48 49 // String data = "我是大好人啊"; 50 // udpChannel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(data.getBytes(Charset.forName("UTF-8"))), new InetSocketAddress("192.168.2.29", 9008))); 51 52 Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { 53 @Override 54 public void run() { 55 nioEventLoopGroup.shutdownGracefully(); 56 } 57 })); 58 } 59 }