从零学Netty(九)Netty实现UDP服务器
简介
- UDP 是User Datagram Protocol的简称, 中文名是用户数据报协议
- UDP协议与TCP协议一样用于处理数据包,在OSI模型中,两者都位于传输层,处于IP协议的上一层
- UDP有不提供数据包分组、组装和不能对数据包进行排序的缺点,也就是说,当报文发送之后,是无法得知其是否安全完整到达的
- UDP用来支持那些需要在计算机之间传输数据的网络应用
实例demo
服务端实现
/**
* udp服务端
*
* @author LionLi
*/
public class UdpServer {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
// 主线程处理
.channel(NioDatagramChannel.class)
// 广播
.option(ChannelOption.SO_BROADCAST, true)
// 设置读缓冲区为2M
.option(ChannelOption.SO_RCVBUF, 2048 * 1024)
// 设置写缓冲区为1M
.option(ChannelOption.SO_SNDBUF, 1024 * 1024)
.handler(new ChannelInitializer<NioDatagramChannel>() {
@Override
protected void initChannel(NioDatagramChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new NioEventLoopGroup(), new UdpServerHandler());
}
});
ChannelFuture f = bootstrap.bind(8088).sync();
System.out.println("服务器正在监听......");
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}
}
服务端业务处理实现
/**
* 服务端业务处理
*
* @author LionLi
*/
public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) {
System.out.println("服务端接收到消息:" + packet.content().toString(StandardCharsets.UTF_8));
// 向客户端发送消息
ByteBuf byteBuf = Unpooled.copiedBuffer("已经接收到消息!".getBytes(StandardCharsets.UTF_8));
ctx.writeAndFlush(new DatagramPacket(byteBuf, packet.sender()));
}
}
客户端实现
/**
* udp客户端
*
* @author LionLi
*/
public class UdpClient {
public static void main(String[] args) {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioDatagramChannel.class)
.handler(new ChannelInitializer<NioDatagramChannel>() {
@Override
protected void initChannel(NioDatagramChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new UdpClientHandler());
}
});
Channel channel = bootstrap.bind(8089).sync().channel();
InetSocketAddress address = new InetSocketAddress("localhost", 8088);
ByteBuf byteBuf = Unpooled.copiedBuffer("你好服务器".getBytes(StandardCharsets.UTF_8));
channel.writeAndFlush(new DatagramPacket(byteBuf, address)).sync();
channel.closeFuture().await();
} catch (Exception e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
}
}
客户端业务处理
/**
* 客户端业务处理
*
* @author LionLi
*/
public class UdpClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
//接受服务端发送的内容
@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) {
System.out.println("客户端接收到消息:" + packet.content().toString(StandardCharsets.UTF_8));
// 向客户端发送消息
ByteBuf byteBuf = Unpooled.copiedBuffer("你好服务器".getBytes(StandardCharsets.UTF_8));
ctx.writeAndFlush(new DatagramPacket(byteBuf, packet.sender()));
}
}
测试
分别启动服务端与客户端
项目已上传到gitee
地址: netty-demo
如果帮到您了,请帮忙点个star
还没有评论,来说两句吧...