博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
netty使用(5)client_server一发一回阐释ByteBuffer的使用
阅读量:5173 次
发布时间:2019-06-13

本文共 5415 字,大约阅读时间需要 18 分钟。

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
() { @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
() { @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

你可能感兴趣的文章
Android Volley 的基本使用/设置HTTP请求参数、apikey
查看>>
Hibernate框架
查看>>
Vim编辑器的使用总结
查看>>
ArcGIS REST 缓存清除(地图空白不显示的问题 )
查看>>
第0次作业
查看>>
"类" 库添加继承
查看>>
ucos在s3c2410上运行过程整体剖析之基础知识-与UCOS运行有关的ARM9芯片知识--续 ...
查看>>
存储器的寻址问题 分类: 计算机组成原理 2011-...
查看>>
DDRmenu(翻译)
查看>>
atitit.文件上传带进度条的实现原理and组件选型and最佳实践总结O7
查看>>
Atitit 架构的原则attilax总结
查看>>
和讯网包容且务实
查看>>
ASP.Net之数据绑定
查看>>
Android自动化测试第三季第二讲Toast控件文字获取
查看>>
Google Analytics的能与不能
查看>>
Ubuntu 基本操作
查看>>
JAVA数组的定义及用法
查看>>
18寒假第七测
查看>>
帧中继
查看>>
105:MyBatis常见实用面试题整理
查看>>