北京哪个网站制作公司,优化大师免费安装下载,全球华设计大赛,wordpress 联系方式前言 在netty数据传输过程中可以有很多选择#xff0c;比如#xff1b;字符串、json、xml、java对象#xff0c;但为了保证传输的数据具备#xff1b;良好的通用性、方便的操作性和传输的高性能#xff0c;我们可以选择protobuf作为我们的数据传输格式。目前protobuf可以支… 前言 在netty数据传输过程中可以有很多选择比如字符串、json、xml、java对象但为了保证传输的数据具备良好的通用性、方便的操作性和传输的高性能我们可以选择protobuf作为我们的数据传输格式。目前protobuf可以支持C、C#、Dart、Go、Java、Python等也可以在JS里使用。知识点ProtobufDecoder、ProtobufEncoder、ProtobufVarint32FrameDecoder、ProtobufVarint32LengthFieldPrepender。 public class MyChannelInitializer extends ChannelInitializerSocketChannel {Overrideprotected void initChannel(SocketChannel channel) throws Exception {//protobuf 处理channel.pipeline().addLast(new ProtobufVarint32FrameDecoder());channel.pipeline().addLast(new ProtobufDecoder(MsgBody.getDefaultInstance()));channel.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());channel.pipeline().addLast(new ProtobufEncoder());// 在管道中添加我们自己的接收数据实现方法channel.pipeline().addLast(new MyClientHandler());}
}public class MyClientHandler extends ChannelInboundHandlerAdapter {/*** 当客户端主动链接服务端的链接后这个通道就是活跃的了。也就是客户端与服务端建立了通信通道并且可以传输数据*/Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {SocketChannel channel (SocketChannel) ctx.channel();System.out.println(链接报告开始);System.out.println(链接报告信息本客户端链接到服务端。channelId channel.id());System.out.println(链接报告IP: channel.localAddress().getHostString());System.out.println(链接报告Port: channel.localAddress().getPort());System.out.println(链接报告完毕);//通知客户端链接建立成功String str 通知服务端链接建立成功 new Date() channel.localAddress().getHostString();ctx.writeAndFlush(MsgUtil.buildMsg(channel.id().toString(), str));}/*** 当客户端主动断开服务端的链接后这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据*/Overridepublic void channelInactive(ChannelHandlerContext ctx) throws Exception {System.out.println(断开链接 ctx.channel().localAddress().toString());}Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {//接收msg消息{与上一章节相比此处已经不需要自己进行解码}System.out.println(new SimpleDateFormat(yyyy-MM-dd HH:mm:ss).format(new Date()) 接收到消息类型 msg.getClass());System.out.println(new SimpleDateFormat(yyyy-MM-dd HH:mm:ss).format(new Date()) 接收到消息内容 JsonFormat.printToString((MsgBody) msg));}/*** 抓住异常当发生异常的时候可以做一些相应的处理比如打印日志、关闭链接*/Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {ctx.close();System.out.println(异常信息\r\n cause.getMessage());}}
public class NettyClient {public static void main(String[] args) {new NettyClient().connect(127.0.0.1, 7397);}private void connect(String inetHost, int inetPort) {EventLoopGroup workerGroup new NioEventLoopGroup();try {Bootstrap b new Bootstrap();b.group(workerGroup);b.channel(NioSocketChannel.class);b.option(ChannelOption.AUTO_READ, true);b.handler(new MyChannelInitializer());ChannelFuture f b.connect(inetHost, inetPort).sync();System.out.println( client start done. {关注明哥获取源码});f.channel().writeAndFlush(MsgUtil.buildMsg(f.channel().id().toString(),你好使用protobuf通信格式的服务端我是明哥关注我获取案例源码。));f.channel().writeAndFlush(MsgUtil.buildMsg(f.channel().id().toString(),你好使用protobuf通信格式的服务端我是明哥关注我获取案例源码。));f.channel().writeAndFlush(MsgUtil.buildMsg(f.channel().id().toString(),你好使用protobuf通信格式的服务端我是明哥关注我获取案例源码。));f.channel().writeAndFlush(MsgUtil.buildMsg(f.channel().id().toString(),你好使用protobuf通信格式的服务端我是明哥关注我获取案例源码。));f.channel().writeAndFlush(MsgUtil.buildMsg(f.channel().id().toString(),你好使用protobuf通信格式的服务端我是明哥关注我获取案例源码。));f.channel().closeFuture().sync();} catch (InterruptedException e) {e.printStackTrace();} finally {workerGroup.shutdownGracefully();}}}
public class MyChannelInitializer extends ChannelInitializerSocketChannel {Overrideprotected void initChannel(SocketChannel channel) {//protobuf 处理channel.pipeline().addLast(new ProtobufVarint32FrameDecoder());channel.pipeline().addLast(new ProtobufDecoder(MsgBody.getDefaultInstance()));channel.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());channel.pipeline().addLast(new ProtobufEncoder());// 在管道中添加我们自己的接收数据实现方法channel.pipeline().addLast(new MyServerHandler());}}public class MyServerHandler extends ChannelInboundHandlerAdapter {/*** 当客户端主动链接服务端的链接后这个通道就是活跃的了。也就是客户端与服务端建立了通信通道并且可以传输数据*/Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {SocketChannel channel (SocketChannel) ctx.channel();System.out.println(链接报告开始);System.out.println(链接报告信息有一客户端链接到本服务端。channelId channel.id());System.out.println(链接报告IP: channel.localAddress().getHostString());System.out.println(链接报告Port: channel.localAddress().getPort());System.out.println(链接报告完毕);//通知客户端链接建立成功String str 通知客户端链接建立成功 new Date() channel.localAddress().getHostString() \r\n;ctx.writeAndFlush(MsgUtil.buildMsg(channel.id().toString(), str));}/*** 当客户端主动断开服务端的链接后这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据*/Overridepublic void channelInactive(ChannelHandlerContext ctx) throws Exception {System.out.println(客户端断开链接 ctx.channel().localAddress().toString());}Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {//接收msg消息{与上一章节相比此处已经不需要自己进行解码}System.out.println(new SimpleDateFormat(yyyy-MM-dd HH:mm:ss).format(new Date()) 接收到消息类型 msg.getClass());System.out.println(new SimpleDateFormat(yyyy-MM-dd HH:mm:ss).format(new Date()) 接收到消息内容 JsonFormat.printToString((MsgBody) msg));}/*** 抓住异常当发生异常的时候可以做一些相应的处理比如打印日志、关闭链接*/Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {ctx.close();System.out.println(异常信息\r\n cause.getMessage());}}public class NettyServer {public static void main(String[] args) {new NettyServer().bing(7397);}private void bing(int port) {//配置服务端NIO线程组EventLoopGroup parentGroup new NioEventLoopGroup(); //NioEventLoopGroup extends MultithreadEventLoopGroup Math.max(1, SystemPropertyUtil.getInt(io.netty.eventLoopThreads, NettyRuntime.availableProcessors() * 2));EventLoopGroup childGroup new NioEventLoopGroup();try {ServerBootstrap b new ServerBootstrap();b.group(parentGroup, childGroup).channel(NioServerSocketChannel.class) //非阻塞模式.option(ChannelOption.SO_BACKLOG, 128).childHandler(new MyChannelInitializer());ChannelFuture f b.bind(port).sync();System.out.println(server start done. {关注我是明哥获取源码});f.channel().closeFuture().sync();} catch (InterruptedException e) {e.printStackTrace();} finally {childGroup.shutdownGracefully();parentGroup.shutdownGracefully();}}} public class MsgUtil {/*** 构建protobuf消息体*/public static MsgBody buildMsg(String channelId, String msgInfo) {MsgBody.Builder msg MsgBody.newBuilder();msg.setChannelId(channelId);msg.setMsgInfo(msgInfo);return msg.build();}}
测试结果 操作idea选中E:\itstack\GIT\itstack.org\itstack-demo-netty\itstack-demo-netty-2-02\protoc-3.5.0-win32\bin 命令protoc -I源地址 --java_out目标地址 源地址/xxx.proto
E:demo-netty\itstack-demo-netty-2-02\protoc-3.5.0-win32\binprotoc.exe -Idemo-netty\itstack-demo-netty-2-02\src\main\java\org\itstack\demo\netty\proto --java_outdemo-netty\netty-2-02\src\main
\java MsgInfo.proto
启动NettyServer
启动NettyClient 服务端执行结果 客户端执行结果 好了到这里就结束netty之Netty使用Protobuf传输数据的学习大家一定要跟着动手操作起来。需要的源码的 可si我获取