netty: 以默认的ByteBuf作为传输数据
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作为传输数据的更多相关文章
- Netty 系列三(ByteBuf).
一.概述和原理 网络数据传输的基本单位总是字节,Netty 提供了 ByteBuf 作为它的字节容器,既解决了 JDK API 的局限性,又为网络应用程序提供了更好的 API,ByteBuf 的优点: ...
- Netty实战五之ByteBuf
网络数据的基本单位总是字节,Java NIO 提供了ByteBuffer作为它的字节容器,但是其过于复杂且繁琐. Netty的ByteBuffer替代品是ByteBuf,一个强大的实现,即解决了JDK ...
- 【Netty技术专题】「原理分析系列」Netty强大特性之ByteBuf零拷贝技术原理分析
零拷贝Zero-Copy 我们先来看下它的定义: "Zero-copy" describes computer operations in which the CPU does n ...
- Netty(7)源码-ByteBuf
一.ByteBuf工作原理 1. ByteBuf是ByteBuffer的升级版: jdk中常用的是ByteBuffer,从功能角度上,ByteBuffer可以完全满足需要,但是有以下缺点: ByteB ...
- netty系列之:EventLoop,EventLoopGroup和netty的默认实现
目录 简介 EventLoopGroup和EventLoop EventLoopGroup在netty中的默认实现 EventLoop在netty中的默认实现 总结 简介 在netty中不管是服务器端 ...
- Netty 核心容器之ByteBuf 结构详解
原文链接 Netty 核心容器之ByteBuf 结构详解 代码仓库地址 Java的NIO模块提供了ByteBuffer作为其字节存储容器,但是这个类的使用过于复杂,因此Netty实现了ByteBuf来 ...
- netty系列之:netty中的ByteBuf详解
目录 简介 ByteBuf详解 创建一个Buff 随机访问Buff 序列读写 搜索 其他衍生buffer方法 和现有JDK类型的转换 总结 简介 netty中用于进行信息承载和交流的类叫做ByteBu ...
- netty中的ByteBuf
网络数据的基本单位总是字节.Java NIO 提供了 ByteBuffer 作为它 的字节容器,但是这个类使用起来过于复杂,而且也有些繁琐. Netty 的 ByteBuffer 替代品是 ByteB ...
- Netty学习篇⑥--ByteBuf源码分析
什么是ByteBuf? ByteBuf在Netty中充当着非常重要的角色:它是在数据传输中负责装载字节数据的一个容器;其内部结构和数组类似,初始化默认长度为256,默认最大长度为Integer.MAX ...
随机推荐
- SQL——WHERE子句
一.WHERE字句的基本用法 WHERE字句用于筛选数据,提取满足条件的记录. WHERE字句的基本用法: SELECT * from 表名 WHERE 条件语句; 二.WHERE字句与删改查 演示s ...
- 24 枚举Enum类
引用声明:部分内容来自文章:http://c.biancheng.net/view/1100.html 枚举Enum类是java.lang下的一个类. 枚举的命名规范 枚举名:大驼峰 枚举值:全大写, ...
- C++ 多态详解及常见面试题
今天,讲一讲多态: 多态就是不同对象对同一行为会有不同的状态.(举例 : 学生和成人都去买票时,学生会打折,成人不会) 实现多态有两个条件: 一是虚函数重写,重写就是用来设置不同状态的 二是对象调 ...
- Java开发环境的搭建02——IntelliJ IDEA篇(Windows)
1.IntelliJ IDEA的下载与安装 IntelliJ IDEA简称IDEA,由JetBrains公司开发,是java语言开发的集成环境,也是目前业界被公认的最好的java开发工具之一.尤其在智 ...
- 【LEETCODE】39、第561题 Array Partition I
package y2019.Algorithm.array; /** * @ProjectName: cutter-point * @Package: y2019.Algorithm.array * ...
- js调用浏览器复制
<script type="text/javascript"> function copyUrl2() { var Url2=document.getElementBy ...
- C# vb .net实现色调调整特效滤镜
在.net中,如何简单快捷地实现Photoshop滤镜组中的色调调整呢?答案是调用SharpImage!专业图像特效滤镜和合成类库.下面开始演示关键代码,您也可以在文末下载全部源码: 设置授权 第一步 ...
- ZeroMQ自查手册
简介 ZMQ (以下 ZeroMQ 简称 ZMQ)是一个简单好用的传输层,像框架一样的一个 socket library,他使得 Socket 编程更加简单.简洁和性能更高.是一个消息处理队列库,可在 ...
- influxdb系列:一、influxdb概念
根据influxdb的官方文档介绍,它是一个时间序列数据库,但是仅仅从名字却不知道它跟已有的关系型数据库有什么区别? 当学习一个新的东西的时候,我的习惯往往是想知道它和我已掌握的知识的对比关系,这样子 ...
- Android应用通过JDBC直连阿里云MySQL数据库
1.设置白名单,获取外网连接地址 外部设备要访问阿里云MySQL数据库,则需要设置白名单,具体操作链接: https://help.aliyun.com/document_detail/43185.h ...