我们可能都学过Socket通信/io/nio/aio等的编程。如果想把Socket真正的用于实际工作中去,那么还需要不断的完善、扩展和优化。比如很经典的Tcp读包写包问题,或者是数据接收的大小,实际的通信读取与应答的处理逻辑等等。当细节问题需要我们认真的去思考,而这些我们都需要大量的时间和精力,以及丰富的经验。

所以想学好socket通信不是件容易的事情。那么现在,我们就需要学习一门新的技术Netty

我们为什么选择Netty?原因是它简单。我们再也不需要去编写复杂的代码和逻辑去实现通信;我们再也不需要去考虑性能问题;我们再也不需要考虑编解码问题、半包读写等问题。这些强大的功能Netty已经帮我们实现了,我们只需要使用它即可!

Netty是目前最流行的NIO框架,它的健壮性、功能、性能、可定制性和可扩展性在同类框架中都是首屈一指的。

Netty已经得到成百上千的商业/商用项目验证,如Hadoop的RPC框架Avro、以及我们之后学习的JMS框架,强大的RocketMQ、还有主流的分布式通信框架Dubbox等等。

Netty5废弃的原因
Netty5可能底层有一些小问题,可能版本更新太快了,然后他把Netty5起了一个分支叫Netty4.1。

Netty架构图

Netty特性

设计:各种传输类型,阻塞和非阻塞的套接字统一的API使用灵活简单但功能强大的线程模型无连接的DatagramSocket支持链逻辑,易于重用。

易于使用:提供大量的文档例子,处理依赖JDK1.6+,没有其他任何的依赖关系,某些功能依赖JDK1.7+,其他特定可能有相关依赖,但都是可选的!

性能:比Java APIS更好的吞吐量和更低的延迟,因为线程池和重用所以消耗较小的资源,尽量减少不必要的内存拷贝。

健壮性:健壮性连接快或慢或超载不会导致更多的内存溢出错误,在高速的网络环境中不会不公平的读或写

安全性:完整的SSL/TLS和StartTLS支持可以在OSGI等的受限制的环境中运行。

社区:版本发布频繁,社区活跃。

对应Netty的介绍就到这里,下面使用Netty框架实现一个HelloWorld。

第一步:下载Netty的jar包

这里使用的是Netty4.1版本。官网下载地址:https://netty.io/downloads.html

第二步:新建java工程

1、新建一个java工程,按照下图新建4个类

2、新建一个lib目录并把Netty的jar包拷贝到该目录

3、把jar包添加到环境变量

第三步:编写ServerHandler类代码,代码如下

 package netty.helloworld;

 import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter; public class ServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("server channel active... ");
} @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf) msg;
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req, "utf-8");
System.out.println("Server :" + body );
String response = "进行返回给客户端的响应:" + body;
ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
} @Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("读完了");
ctx.flush();
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable t) throws Exception {
ctx.close();
}
}

ServerHandler.java

第四步:编写Server类代码,代码如下

 package netty.helloworld;

 import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
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; public class Server {
public static void main(String[] args) throws Exception {
// 1 创建线两个程组
// 一个是用于处理服务器端接收客户端连接的
// 一个是进行网络通信的(网络读写的)
EventLoopGroup pGroup = new NioEventLoopGroup();
EventLoopGroup cGroup = new NioEventLoopGroup(); // 2 创建辅助工具类,用于服务器通道的一系列配置
ServerBootstrap b = new ServerBootstrap();
b.group(pGroup, cGroup) // 绑定俩个线程组
.channel(NioServerSocketChannel.class) // 指定NIO的模式
.option(ChannelOption.SO_BACKLOG, 1024) // 设置tcp缓冲区
.option(ChannelOption.SO_SNDBUF, 32*1024) // 设置发送缓冲大小
.option(ChannelOption.SO_RCVBUF, 32*1024) // 这是接收缓冲大小
.option(ChannelOption.SO_KEEPALIVE, true) // 保持连接
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel sc) throws Exception {
// 3 在这里配置具体数据接收方法的处理
sc.pipeline().addLast(new ServerHandler());
}
}); // 4 进行绑定
ChannelFuture cf1 = b.bind(8888).sync();
// 5 等待关闭
cf1.channel().closeFuture().sync();
pGroup.shutdownGracefully();
cGroup.shutdownGracefully();
}
}

Server.java

第五步:编写ClientHandler类代码,代码如下

 package netty.helloworld;

 import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil; public class ClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {} @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
ByteBuf buf = (ByteBuf) msg; byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req); String body = new String(req, "utf-8");
System.out.println("Client :" + body );
} finally {
ReferenceCountUtil.release(msg);
}
} @Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}

ClientHandler.java

第六步:编写Client类代码,代码如下

 package netty.helloworld;

 import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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 Client {
public static void main(String[] args) throws Exception{
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel sc) throws Exception {
sc.pipeline().addLast(new ClientHandler());
}
}); ChannelFuture cf1 = b.connect("127.0.0.1", 8888).syncUninterruptibly();
// 发送消息
byte[] msg = "发送第1条测试消息".getBytes();
cf1.channel().writeAndFlush(Unpooled.copiedBuffer(msg)); // 等待关闭
cf1.channel().closeFuture().sync();
group.shutdownGracefully();
}
}

Client.java

第七步:启动Server服务

最后一步:启动客户端

控制台输出

关于Netty框架学习的第一节课就讲到这里,其他更多关于Netty方面的教程后续会陆续更新!!

end -- 1346ac475e98aed

需要索取完整源码或者其他任何有关技术问题和疑问,直接wxhaox

最新文章

  1. xenomai for at91
  2. rem自适应布局的回顾总结
  3. lr常用
  4. git原理图解
  5. arraylist 转json
  6. 使用SVG Path绘图
  7. 第一章 :绪论-Twitter数据的收集和处理
  8. (一)Windows下搭建PHP开发环境及相关注意事项
  9. chrome dev tools
  10. 定时每天备份mysql
  11. Eclipse:The selection cannot be launched,and there are no recent launches
  12. 在ASP.NET Core 中使用Cookie中间件
  13. String.prototype.trim
  14. Oracle和Mysql获取uuid的方法对比
  15. Bring up a Kafka-based Ordering Service
  16. linux 怎么与网络对时
  17. 使用VSCode如何调试C#控制台程序_2_加深总结
  18. tomcat目录映射
  19. Java中Reflect的基本使用
  20. 学习笔记TF045:人工智能、深度学习、TensorFlow、比赛、公司

热门文章

  1. 爬取豆瓣Top250_Ajax动态页面
  2. Http协议——基本概念
  3. golang json 示例
  4. java处理excel
  5. 《Scrum实战》第3次课【富有成效的每日站会】作业汇总
  6. 02 Java 的基本类型
  7. [python工具][1]sublime安装与配置
  8. [错误处理]python大小写敏感,关键字不要写错
  9. Spring 4.3.11.RELEASE文档阅读(一):overview
  10. curl 设置头部