庆幸的是借助getty良好的设计模式,getty udp的使用方式与tcp差别不大。
唯一的区别就是需要指定socketChannel为UDP。默认不指定是TCP
需要指定UDP的消息编解码器
//对于UDP而言,只有DatagramPacketEncoder、DatagramPacketDecoder两个处理器是有效的
//原因在于UDP本身不存在连接,因而其他处理器即使配置了也是没有效果的
defaultChannelPipeline.addLast(new DatagramPacketEncoder());
defaultChannelPipeline.addLast(new DatagramPacketDecoder());
//服务器端
AioServerStarter server = new AioServerStarter(8888);
//唯一的区别就是需要指定socketChannel为UDP。默认不指定是TCP
server.socketChannel(SocketChannel.UDP).channelInitializer(new ChannelInitializer() {
@Override
public void initChannel(AioChannel channel) throws Exception {
//获取责任链对象
DefaultChannelPipeline defaultChannelPipeline = channel.getDefaultChannelPipeline();
//对于UDP而言,只有DatagramPacketEncoder、DatagramPacketDecoder两个处理器是有效的
//原因在于UDP本身不存在连接,因而其他处理器即使配置了也是没有效果的
defaultChannelPipeline.addLast(new DatagramPacketEncoder());
defaultChannelPipeline.addLast(new DatagramPacketDecoder());
//添加自定义的简单消息处理器
defaultChannelPipeline.addLast(new SimpleHandler());
}
}).start();
------------------------------------------------------------------
//客户端
AioClientConfig aioConfig = new AioClientConfig();
//Host与port无需指定也没有关系,指定了也没有效果
aioConfig.setHost("127.0.0.1");
aioConfig.setPort(port);
aioConfig.setClientChunkSize(512 * 1024 * 1024);
aioConfig.setBufferWriterQueueSize(2 * 1024 * 1024);
AioClientStarter client = new AioClientStarter(aioConfig);
client.socketChannel(SocketChannel.UDP).channelInitializer(new ChannelInitializer() {
@Override
public void initChannel(AioChannel channel) throws Exception {
//责任链
DefaultChannelPipeline defaultChannelPipeline = channel.getDefaultChannelPipeline();
defaultChannelPipeline.addLast(new DatagramPacketEncoder());
defaultChannelPipeline.addLast(new DatagramPacketDecoder());
//定义消息解码器
defaultChannelPipeline.addLast(new SimpleHandler());
}
});
try {
client.start();
} catch (Exception e) {
e.printStackTrace();
}
//发送个消息给服务器
Thread.sleep(2000);
AioChannel aioChannel = client.getAioChannel();
String s = "hello getty";
byte[] msgBody = s.getBytes("utf-8");
//UDP消息发送的是DatagramPacket 发送的目标服务器在DatagramPacket 中指定
DatagramPacket datagramPacket = new DatagramPacket(msgBody, msgBody.length, new InetSocketAddress("127.0.0.1", 8888));
aioChannel.writeAndFlush(datagramPacket);
SimpleHandler的类型指定为 > DatagramPacket
public class SimpleHandler extends SimpleChannelInboundHandler<DatagramPacket> {
@Override
public void channelAdded(AioChannel aioChannel) {
System.out.println("连接成功");
}
@Override
public void channelClosed(AioChannel aioChannel) {
System.out.println("连接关闭了");
}
@Override
public void channelRead0(AioChannel aioChannel, DatagramPacket datagramPacket) {
System.out.println("读取消息了:" + new String(datagramPacket.getData()));
System.out.println("客户端地址:" + datagramPacket.getAddress().getHostName() + ":" + datagramPacket.getPort());
}
@Override
public void exceptionCaught(AioChannel aioChannel, Throwable cause, PipelineDirection pipelineDirection) {
System.out.println("出错了");
}
}