client部分代码:

//线程
EventLoopGroup worker = new NioEventLoopGroup();
//辅助类
Bootstrap b = new Bootstrap();
//注册server
b.group(worker)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() { @Override
protected void initChannel(SocketChannel sc) throws Exception {
// TODO Auto-generated method stub
sc.pipeline().addLast(new ClientHandler());
}
});

  

clientHandler部分代码:

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// TODO Auto-generated method stub
try {
ByteBuf buf = (ByteBuf)msg;
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
String result = new String(bytes, "utf-8");
System.out.println("Server: " + result);
}finally {
ReferenceCountUtil.release(msg);
} }

  

下面查看完整代码 :

client:

public static void main(String[] args) throws InterruptedException {

		//线程
EventLoopGroup worker = new NioEventLoopGroup();
//辅助类
Bootstrap b = new Bootstrap();
//注册server
b.group(worker)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() { @Override
protected void initChannel(SocketChannel sc) throws Exception {
// TODO Auto-generated method stub
//不做任何处理,ByteBuf格式传输
sc.pipeline().addLast(new ClientHandler());
}
}); ChannelFuture cf = b.connect("127.0.0.1", 8765).sync(); cf.channel().writeAndFlush(Unpooled.copiedBuffer("hello netty!!".getBytes()));
// Thread.sleep(1000);
// cf.channel().writeAndFlush(Unpooled.copiedBuffer("hello netty!!".getBytes()));
// Thread.sleep(1000);
// cf.channel().writeAndFlush(Unpooled.copiedBuffer("hello netty!!".getBytes()));
//发送完毕,断开连接
cf.addListener(ChannelFutureListener.CLOSE); cf.channel().closeFuture().sync();
worker.shutdownGracefully(); }

  

clientHandler代码:

需要继承:ChannelHandlerAdapter这个类

public class ClientHandler extends ChannelHandlerAdapter {

	@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// TODO Auto-generated method stub
try { //原始ByteBuf数据格式处理
ByteBuf buf = (ByteBuf)msg;
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
String result = new String(bytes, "utf-8");
System.out.println("Server: " + result);
}finally { //接收处理完后,丢弃
ReferenceCountUtil.release(msg);
} } @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// TODO Auto-generated method stub
cause.printStackTrace();
ctx.close();
} }

  

Server代码:

public static void main(String[] args) throws InterruptedException {

		//第一个线程连接client端
EventLoopGroup boss = new NioEventLoopGroup();
//第二个线程处理逻辑
EventLoopGroup worker = new NioEventLoopGroup();
//辅助类,注册 server
ServerBootstrap b = new ServerBootstrap();
b.group(boss, worker)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() { @Override
protected void initChannel(SocketChannel sc) throws Exception {
// TODO Auto-generated method stub
sc.pipeline().addLast(new ServerHandler());
}
}); //绑定指定的端口方便监听
ChannelFuture cf = b.bind(8765).sync();
cf.channel().closeFuture().sync(); boss.shutdownGracefully();
worker.shutdownGracefully(); }

  

serverHandler代码:

需要继承:ChannelHandlerAdapter 类

public class ServerHandler extends ChannelHandlerAdapter {

	@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// TODO Auto-generated method stub
ByteBuf buf = (ByteBuf)msg;
byte[] bs = new byte[buf.readableBytes()];
buf.readBytes(bs);
String result = new String(bs, "utf-8");
System.out.println("Client: " + result); String response = "888888";
ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
//.addListener(ChannelFutureListener.CLOSE); } @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// TODO Auto-generated method stub
cause.printStackTrace();
ctx.close();
} }

  

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. !与&&优先级的问题

    逻辑否(!)是一元操作符,逻辑与(&&)是二元操作符,一元操作符的优先级高于任何二元操作符. 例如: bool flag:int t: if(!flag && t &g ...

  2. vue通过ajax加载json数据

    HTML <ul id="Hanapp"> <li class="styVue" v-for="item in actList&qu ...

  3. Selenium自动化获取WebSocket信息

    性能日志 ChromeDriver支持性能日志记录,您可以从中获取域“时间轴”,“网络”和“页面”的事件,以及指定跟踪类别的跟踪数据. 启用性能日志 默认情况下不启用性能日志记录.因此,在创建新会话时 ...

  4. Hibernate-validator数据验证

    前言 数据效验工作在开发工作中,是非常重要的,保证数据的正确性,可靠性,安全性.不仅在前端进行效验,还要在后台继续进行效验. 前端做验证只是为了用户体验,比如控制按钮的显示隐藏,单页应用的路由跳转等等 ...

  5. 跨域和CORS

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

  6. JavaScript中的原型prototype和__proto__的区别及原型链概念

    问题 初学js的同学,总是搞不清楚js中的原型是什么东西,看着控制台打印出来的一串串__proto__,迷惑不已. 例如我定义一个Person,创建一个实例p,并打印实例. function Pers ...

  7. Unity3D 跨平台原理

    Unity3D的跨平台原理核心在于对指令集CIL(通用中间语言)的应用. 机理 首先需要知道,Unity中的Mono是基于 通用语言架构(Common Language Infrastructure, ...

  8. logback 生成 catalina.base_IS_UNDEFINED 问题处理 &如何在eclipse/idea中添加VM参数

    1>在Eclipse中里设置  windows->preferences->Java->Installed JRES->edit->Default VM Argum ...

  9. java之hibernate之基于外键的一对一单向关联映射

    这篇讲解基于外键的一对一单向关联映射 1.考察如下信息,人和身份证之间是一个一对一的关系.表的设计 注意:基于外键的一对一关联的表结构和多对一的表结构是一致的,但是,外键是唯一的. 2.类的结构 Pe ...

  10. 3.MVC基础-Code First 入门完整实例

    1.添加一个EF的上下文类  EFDbContext public class EFDbContext:DbContext { public EFDbContext() : base("EF ...