netty使用(5)client_server一发一回阐释ByteBuffer的使用
Client 连接 发送一句问候,Server打印Client的问候,返回
I am ok!后关闭连接,Client打印Server发送的I am ok!
Server代码
package simpleDialogServer;import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; 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; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; public class HelloServer { public void start(int port) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { // 注册handler ch.pipeline().addLast(new HelloServerInHandler()); } }).option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(port).sync(); f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { HelloServer server = new HelloServer(); server.start(8000); } }// 该handler是InboundHandler类型 class HelloServerInHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf result = (ByteBuf) msg; byte[] result1 = new byte[result.readableBytes()]; // msg中存储的是ByteBuf类型的数据,把数据读取到byte[]中 result.readBytes(result1); String resultStr = new String(result1); // 接收并打印客户端的信息 System.out.println("Client said:" + resultStr); // 释放资源,这行很关键 result.release(); // 向客户端发送消息 String response = "I am ok!"; // 在当前场景下,发送的数据必须转换成ByteBuf数组 ByteBuf encoded = ctx.alloc().buffer(4 * response.length()); encoded.writeBytes(response.getBytes()); ctx.write(encoded); ctx.flush(); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush();ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);} }
Client代码
package simpleDialogClient; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; 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 HelloClient { 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 HelloClientIntHandler()); } }); // Start the client. ChannelFuture f = b.connect(host, port).sync(); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { HelloClient client = new HelloClient(); client.connect("127.0.0.1", 8000); } } class HelloClientIntHandler extends ChannelInboundHandlerAdapter { // 接收server端的消息,并打印出来 @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf result = (ByteBuf) msg; byte[] result1 = new byte[result.readableBytes()]; result.readBytes(result1); System.out.println("Server said:" + new String(result1)); result.release(); } // 连接成功后,向server发送消息 @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { String msg = "Are you ok?"; ByteBuf encoded = ctx.alloc().buffer(4 * msg.length()); encoded.writeBytes(msg.getBytes()); ctx.write(encoded); ctx.flush(); } }
转载于:https://www.cnblogs.com/legion/p/8674330.html
netty使用(5)client_server一发一回阐释ByteBuffer的使用相关推荐
- Netty 从源码的角度深入剖析 ByteBuffer
如何从源码的角度深入剖析ByteBuffer 你只看见了调用一个方法就能创建符合要求的 ByteBuf 却不知为何如此简单, 你只看见了 Netty 使用了线程池却不知线程池用的是什么队列 你只看见了 ...
- Netty-案例 WebSocket与netty实现长连接案例(代码注释详解)
Netty 记录学习,开心学习,来源尚硅谷韩顺平netty视频 1 NettyServer package com.fs.netty.simple;import io.netty.bootstrap. ...
- 尚硅谷Netty学习笔记
Netty 一些问题 1.阻塞与非阻塞 阻塞和非阻塞指的是执行一个操作是等操作结束再返回,还是马上返回 举例:在 BIO 案例的 handler 方法中,如果读取不到数据就会阻塞在 read() 方法 ...
- Netty入门-第二话
文章目录 Netty 概述 原生 NIO 存在的问题 Netty 官网说明 Netty 的优点 Netty 版本说明 Netty 高性能架构设计 线程模型基本介绍 传统阻塞 I/O 服务模型 工作原理 ...
- 6、Netty 高性能架构设计
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 Netty概述 原生NIO存在的问题 Netty官网说明 Netty的优点 Netty版本说明 线程模型基本介绍 传统阻塞 ...
- Netty 核心组件源码剖析
文章目录 1.EventLoopGroup 1.1 NioEventLoopGroup 1.2 NioEventLoop 1.2.1 NioEventLoop 开启 Selector 1.2.2 Ni ...
- Netty详解(七):Netty 编解码以及消息头编解码器
1. MessagePack 概述 MessagePack是一个高效的二进制序列化框架,像JSON一样支持不同语言间的数据交换,速度更快,序列化之后的码流更小. MessagePacke优点 编解码高 ...
- Netty出现的原因以及多种Reactor模式
一.原生NIO存在的问题 NIO的类库与API繁杂,需要熟练掌握Selector.ServerSocketChannel.SocketChannel.Bytebuffer等要求熟悉Java多线程编程和 ...
- netty系列之:netty架构概述
文章目录 简介 netty架构图 丰富的Buffer数据机构 零拷贝 统一的API 事件驱动 其他优秀的特性 总结 简介 Netty为什么这么优秀,它在JDK本身的NIO基础上又做了什么改进呢?它的架 ...
- 45 张图深度解析 Netty 架构与原理
作为一个学 Java 的,如果没有研究过 Netty,那么你对 Java 语言的使用和理解仅仅停留在表面水平,会点 SSH 写几个 MVC,访问数据库和缓存,这些只是初等 Java 程序员干的事.如果 ...
最新文章
- shell去除字符串前所有的0
- 软件项目经理需具备什么样的技术水平?
- c语言高函数正确形式,计算机二级C语言考点解析:函数
- 学成在线--2.CMS前端页面查询开发
- 【活体检测】二分类活体检测评价方式
- sql查询去除视图重复项_如何使用SQL查询视图,Postico使用技巧分享
- linux 云主机安装方法,虚拟主机linux服务器安装教程
- mysql常用四种连接_MySQL四种连接查询
- HDU1517 A Multiplication Game (博弈论+思维)
- 标准工时分析软件VIOOVI,适配现代化工业的人工智能软件
- 实现echarts中国地图迁徙图
- GridView排序
- idea项目工具窗口
- 【迪文屏】踩坑指南——汉字显示乱码、背景图不显示问题的解决方法
- Minor GC、Young GC、Old GC、Major GC、Mixed GC、Full GC都是什么?
- hive之生成唯一id
- GAN-overview reading note(3)Wasserstein GAN
- 苦尽甘来 一个月学通JavaWeb(三十五 数据库)
- 学校计算机教室建设要求,计算机教室施工建设要求
- 记一次软考高项【信息系统项目管理师】重点