版权声明,本文转自:http://www.youbiji.cn/user/hll/1568265752509.html
本实例演示Netty服务端和客户端如何传递消息,你只需要2分钟就可以实现运行自己的第一个Netty程序。请复制粘贴下面的代码到你的开发工具中看看效果吧!
添加maven依赖:
<dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.38.Final</version> </dependency> 服务端消息处理类:
package com.demo.mynetty; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.ReferenceCountUtil; // 消息处理 public class ReceiveServerHandler extends ChannelInboundHandlerAdapter { // 收到消息时自动执行此方法 @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // 读取消息 ByteBuf buf = (ByteBuf)msg; byte[] req = new byte[buf.readableBytes()]; buf.readBytes(req); ReferenceCountUtil.release(msg); String receivedMsg = new String(req, "UTF-8"); System.out.println("服务器收到消息:" + receivedMsg); // 返回消息 ByteBuf respBuf = Unpooled.copiedBuffer("服务器已收到消息".getBytes()); ctx.write(respBuf); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); } }
服务端:
package com.demo.mynetty; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; // 服务端 public class ReceiveServer { // 服务端配置 public void bind(int port) throws Exception { EventLoopGroup parentGroup = new NioEventLoopGroup(); EventLoopGroup childGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.group(parentGroup, childGroup); b.channel(NioServerSocketChannel.class); b.option(ChannelOption.SO_BACKLOG, 1024); b.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ReceiveServerHandler()); } }); try { ChannelFuture f = b.bind(port).sync(); // 阻塞直到服务端的链路关闭后优雅的退出 f.channel().closeFuture().sync(); } finally { // 释放相关资源 parentGroup.shutdownGracefully(); childGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { new ReceiveServer().bind(20199); } }
客户端消息处理类:
package com.demo.mynetty; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.ReferenceCountUtil; // 消息处理 public class SendClientHandler extends ChannelInboundHandlerAdapter { // 收到消息时自动执行此方法 @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // 读取消息 ByteBuf buf = (ByteBuf)msg; byte[] resp = new byte[buf.readableBytes()]; buf.readBytes(resp); // 释放资源 ReferenceCountUtil.release(msg); String respMsg = new String(resp, "UTF-8"); System.out.println(respMsg); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); } }
客户端:
package com.demo.mynetty; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; // 客户端 public class SendClient { // 和服务器建立连接 public void connect(String host, int port) throws Exception { // 配置连接信息 EventLoopGroup workerGroup = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new SendClientHandler()); } }); // 建立连接 ChannelFuture f = b.connect(host, port).sync(); // 发送数据 ByteBuf sendBuf = Unpooled.copiedBuffer("我是客户端001".getBytes()); f.channel().writeAndFlush(sendBuf); // 阻塞直到连接被关闭时优雅的退出 f.channel().closeFuture().sync(); } finally { // 释放相关资源 workerGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { new SendClient().connect("127.0.0.1", 20199); } }
最后先运行服务端main方法,再运行客户端main方法查看效果。