client部分代码:

  1. //线程
  2. EventLoopGroup worker = new NioEventLoopGroup();
  3. //辅助类
  4. Bootstrap b = new Bootstrap();
  5. //注册server
  6. b.group(worker)
  7. .channel(NioSocketChannel.class)
  8. .handler(new ChannelInitializer<SocketChannel>() {
  9.  
  10. @Override
  11. protected void initChannel(SocketChannel sc) throws Exception {
  12. // TODO Auto-generated method stub
  13. sc.pipeline().addLast(new ClientHandler());
  14. }
  15. });

  

clientHandler部分代码:

  1. @Override
  2. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  3. // TODO Auto-generated method stub
  4. try {
  5. ByteBuf buf = (ByteBuf)msg;
  6. byte[] bytes = new byte[buf.readableBytes()];
  7. buf.readBytes(bytes);
  8. String result = new String(bytes, "utf-8");
  9. System.out.println("Server: " + result);
  10. }finally {
  11. ReferenceCountUtil.release(msg);
  12. }
  13.  
  14. }

  

下面查看完整代码 :

client:

  1. public static void main(String[] args) throws InterruptedException {
  2.  
  3. //线程
  4. EventLoopGroup worker = new NioEventLoopGroup();
  5. //辅助类
  6. Bootstrap b = new Bootstrap();
  7. //注册server
  8. b.group(worker)
  9. .channel(NioSocketChannel.class)
  10. .handler(new ChannelInitializer<SocketChannel>() {
  11.  
  12. @Override
  13. protected void initChannel(SocketChannel sc) throws Exception {
  14. // TODO Auto-generated method stub
  15. //不做任何处理,ByteBuf格式传输
  16. sc.pipeline().addLast(new ClientHandler());
  17. }
  18. });
  19.  
  20. ChannelFuture cf = b.connect("127.0.0.1", 8765).sync();
  21.  
  22. cf.channel().writeAndFlush(Unpooled.copiedBuffer("hello netty!!".getBytes()));
  23. // Thread.sleep(1000);
  24. // cf.channel().writeAndFlush(Unpooled.copiedBuffer("hello netty!!".getBytes()));
  25. // Thread.sleep(1000);
  26. // cf.channel().writeAndFlush(Unpooled.copiedBuffer("hello netty!!".getBytes()));
  27. //发送完毕,断开连接
  28. cf.addListener(ChannelFutureListener.CLOSE);
  29.  
  30. cf.channel().closeFuture().sync();
  31. worker.shutdownGracefully();
  32.  
  33. }

  

clientHandler代码:

需要继承:ChannelHandlerAdapter这个类

  1. public class ClientHandler extends ChannelHandlerAdapter {
  2.  
  3. @Override
  4. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  5. // TODO Auto-generated method stub
  6. try {
  7.  
  8. //原始ByteBuf数据格式处理
  9. ByteBuf buf = (ByteBuf)msg;
  10. byte[] bytes = new byte[buf.readableBytes()];
  11. buf.readBytes(bytes);
  12. String result = new String(bytes, "utf-8");
  13. System.out.println("Server: " + result);
  14. }finally {
  15.  
  16. //接收处理完后,丢弃
  17. ReferenceCountUtil.release(msg);
  18. }
  19.  
  20. }
  21.  
  22. @Override
  23. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  24. // TODO Auto-generated method stub
  25. cause.printStackTrace();
  26. ctx.close();
  27. }
  28.  
  29. }

  

Server代码:

  1. public static void main(String[] args) throws InterruptedException {
  2.  
  3. //第一个线程连接client端
  4. EventLoopGroup boss = new NioEventLoopGroup();
  5. //第二个线程处理逻辑
  6. EventLoopGroup worker = new NioEventLoopGroup();
  7. //辅助类,注册 server
  8. ServerBootstrap b = new ServerBootstrap();
  9. b.group(boss, worker)
  10. .channel(NioServerSocketChannel.class)
  11. .childHandler(new ChannelInitializer<SocketChannel>() {
  12.  
  13. @Override
  14. protected void initChannel(SocketChannel sc) throws Exception {
  15. // TODO Auto-generated method stub
  16. sc.pipeline().addLast(new ServerHandler());
  17. }
  18. });
  19.  
  20. //绑定指定的端口方便监听
  21. ChannelFuture cf = b.bind(8765).sync();
  22. cf.channel().closeFuture().sync();
  23.  
  24. boss.shutdownGracefully();
  25. worker.shutdownGracefully();
  26.  
  27. }

  

serverHandler代码:

需要继承:ChannelHandlerAdapter 类

  1. public class ServerHandler extends ChannelHandlerAdapter {
  2.  
  3. @Override
  4. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  5. // TODO Auto-generated method stub
  6. ByteBuf buf = (ByteBuf)msg;
  7. byte[] bs = new byte[buf.readableBytes()];
  8. buf.readBytes(bs);
  9. String result = new String(bs, "utf-8");
  10. System.out.println("Client: " + result);
  11.  
  12. String response = "888888";
  13. ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
  14. //.addListener(ChannelFutureListener.CLOSE);
  15.  
  16. }
  17.  
  18. @Override
  19. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  20. // TODO Auto-generated method stub
  21. cause.printStackTrace();
  22. ctx.close();
  23. }
  24.  
  25. }

  

netty: 以默认的ByteBuf作为传输数据的更多相关文章

  1. Netty 系列三(ByteBuf).

    一.概述和原理 网络数据传输的基本单位总是字节,Netty 提供了 ByteBuf 作为它的字节容器,既解决了 JDK API 的局限性,又为网络应用程序提供了更好的 API,ByteBuf 的优点: ...

  2. Netty实战五之ByteBuf

    网络数据的基本单位总是字节,Java NIO 提供了ByteBuffer作为它的字节容器,但是其过于复杂且繁琐. Netty的ByteBuffer替代品是ByteBuf,一个强大的实现,即解决了JDK ...

  3. 【Netty技术专题】「原理分析系列」Netty强大特性之ByteBuf零拷贝技术原理分析

    零拷贝Zero-Copy 我们先来看下它的定义: "Zero-copy" describes computer operations in which the CPU does n ...

  4. Netty(7)源码-ByteBuf

    一.ByteBuf工作原理 1. ByteBuf是ByteBuffer的升级版: jdk中常用的是ByteBuffer,从功能角度上,ByteBuffer可以完全满足需要,但是有以下缺点: ByteB ...

  5. netty系列之:EventLoop,EventLoopGroup和netty的默认实现

    目录 简介 EventLoopGroup和EventLoop EventLoopGroup在netty中的默认实现 EventLoop在netty中的默认实现 总结 简介 在netty中不管是服务器端 ...

  6. Netty 核心容器之ByteBuf 结构详解

    原文链接 Netty 核心容器之ByteBuf 结构详解 代码仓库地址 Java的NIO模块提供了ByteBuffer作为其字节存储容器,但是这个类的使用过于复杂,因此Netty实现了ByteBuf来 ...

  7. netty系列之:netty中的ByteBuf详解

    目录 简介 ByteBuf详解 创建一个Buff 随机访问Buff 序列读写 搜索 其他衍生buffer方法 和现有JDK类型的转换 总结 简介 netty中用于进行信息承载和交流的类叫做ByteBu ...

  8. netty中的ByteBuf

    网络数据的基本单位总是字节.Java NIO 提供了 ByteBuffer 作为它 的字节容器,但是这个类使用起来过于复杂,而且也有些繁琐. Netty 的 ByteBuffer 替代品是 ByteB ...

  9. Netty学习篇⑥--ByteBuf源码分析

    什么是ByteBuf? ByteBuf在Netty中充当着非常重要的角色:它是在数据传输中负责装载字节数据的一个容器;其内部结构和数组类似,初始化默认长度为256,默认最大长度为Integer.MAX ...

随机推荐

  1. CSS中position 和float的使用说明(清晰)

    当构建页面排版时,有不同的方法可以使用.使用哪一种方法取决于具体页面的排版要求,在不同的情况下,某些方法可能好过于其他的方法. 比如,可以使用若干个浮动元素来构建一个整洁简洁的页面排版.或者,如果需要 ...

  2. 跨域和CORS

    一 跨域 同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响.可以说Web是构建在同源策略基础之上的 ...

  3. 24 枚举Enum类

    引用声明:部分内容来自文章:http://c.biancheng.net/view/1100.html 枚举Enum类是java.lang下的一个类. 枚举的命名规范 枚举名:大驼峰 枚举值:全大写, ...

  4. 关于类视图选择继承APIView还是工具视图(ListAPIView、CreateAPIView等等)

    APIView使用方法,直接继承APIView,get或者post请求.方法很简单1.先获取到要操作的数据,然后把数据放到serializer中序列化或者反序列化,最后return返回值(记得.dat ...

  5. Linux环境下错误码及意义总结

    Linux的错误码包含在/usr/include/asm-generic/errno-base.h和/usr/include/asm-generic/errno.h 这两个文件内: #ifndef _ ...

  6. Helm命令日常使用

    更换仓库 默认的stable仓库地址是:https://kubernetes-charts.storage.googleapis.com 若遇到Unable to get an update from ...

  7. DevOps 什么是 CI/CD?

    CI/CD 是一种通过在应用开发阶段引入自动化来频繁向客户交付应用的方法.CI/CD 的核心概念是持续集成.持续交付和持续部署.作为一个面向开发和运营团队的解决方案,CI/CD 主要针对在集成新代码时 ...

  8. Unity项目 - 简单时钟 Clock

    项目展示 Github项目地址:简单时钟 Clock 制作流程 表盘绘制: 采用Aseprite 像素绘图软件绘制表盘及指针.本例钟表素材大小 256x256,存储格式为png,但发现导入Unity后 ...

  9. php生成一维码以及保存-转载

    地址:http://www.cnblogs.com/ForEvErNoME/archive/2012/04/21/2460944.html 注释掉: //header('Content-Type: i ...

  10. js中for循环点击事件(闭包)

    <!DOCTYPE html><html lang="en"><head> <meta charset="utf-8" ...