【Netty整理01-快速入门】Netty简单使用Demo(已验证)
多处摘抄或手打,为了十积分厚着脸皮标为原创,惭愧惭愧~本篇文章用于快速入门搭建一个简单的netty
应用,如想稍微深入系统的了解,请参照本人下一篇博客,链接:
参考地址:
官方文档:http://netty.io/wiki/user-guide-for-4.x.html
文案部分:
百度百科:https://baike.baidu.com/item/Netty/10061624?fr=aladdin
NIO:https://blog.csdn.net/skiof007/article/details/52873421
代码部分:
https://blog.csdn.net/hangge110/article/details/51613988
更多参考:
各个对象以及常量的作用对照源码:https://blog.csdn.net/CoffeeAndIce/article/details/78987542
源代码学习1:https://www.cnblogs.com/katsura/p/5991428.html
源代码学习2:https://www.cnblogs.com/stevenczp/p/7581940.html
demo02:https://blog.csdn.net/Howinfun/article/details/81283721
Netty
Netty是由JBOSS提供的一个java开源框架。Netty提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客户端程序。
也就是说,Netty 是一个基于NIO的客户、服务器端编程框架,使用Netty 可以确保你快速和简单的开发出一个网络应用,例如实现了某种协议的客户、服务端应用。Netty相当于简化和流线化了网络应用的编程开发过程,例如:基于TCP和UDP的socket服务开发。
NIO基本概念:点击打开链接
IO的方式通常分为几种,同步阻塞的BIO、同步非阻塞的NIO、异步非阻塞的AIO......
DEMO(手打https://blog.csdn.net/hangge110/article/details/51613988):
1、服务端
package com.zx.test;
import com.lk.netty.mulchat.dome.ServerIniterHandler;
import com.lk.netty.mulchat.dome.ServerMain;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.omg.CORBA.PRIVATE_MEMBER;
/**
* 服务端生产者对象
* This is an netty Server
* @author ZX
* @date 2018年6月7日
* Netty中,通讯的双方建立连接后,会把数据按照ByteBuf的方式进行传输,
* 例如http协议中,就是通过HttpRequestDecoder对ByteBuf数据流进行处理,转换成http的对象。
* 深入学习:
* https://www.cnblogs.com/katsura/p/5991428.html
* https://www.cnblogs.com/stevenczp/p/7581940.html
*/
public class ServerTest {
/**
* 服务端口
*/
private int port=9999;
/**
* 开启服务的方法
*/
public void StartNetty(){
/**创建两个EventLoop的组,EventLoop 这个相当于一个处理线程,
是Netty接收请求和处理IO请求的线程。不理解的话可以百度NIO图解*/
/*
相关资料:NioEventLoopGroup是一个处理I/O操作的多线程事件循环。
Netty为不同类型的传输提供了各种EventLoopGroup实现。
在本例中,我们正在实现一个服务器端应用程序,因此将使用两个NioEventLoopGroup。
第一个,通常称为“boss”,接受传入的连接。
第二个,通常称为“worker”,当boss接受连接并注册被接受的连接到worker时,处理被接受连接的流量。
使用了多少线程以及如何将它们映射到创建的通道取决于EventLoopGroup实现,甚至可以通过构造函数进行配置。
*/
EventLoopGroup acceptor = new NioEventLoopGroup();
EventLoopGroup worker = new NioEventLoopGroup();
try {
//1、创建启动类
ServerBootstrap bootstrap = new ServerBootstrap();
//2、配置启动参数等
/**设置循环线程组,前者用于处理客户端连接事件,后者用于处理网络IO(server使用两个参数这个)
*public ServerBootstrap group(EventLoopGroup group)
*public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup)
*/
bootstrap.group(acceptor,worker);
/**设置选项
* 参数:Socket的标准参数(key,value),可自行百度
* eg:
* bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
*bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
* */
bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
//用于构造socketchannel工厂
bootstrap.channel(NioServerSocketChannel.class);
/**
* 传入自定义客户端Handle(服务端在这里搞事情)
*/
bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
// 注册handler
ch.pipeline().addLast(new SimpleServerHandler());
}
});
// 绑定端口,开始接收进来的连接
ChannelFuture f = bootstrap.bind(port).sync();
// 等待服务器 socket 关闭 。
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
acceptor.shutdownGracefully();
worker.shutdownGracefully();
}
}
public static void main(String[] args) {
new ServerTest().StartNetty();
}
}
2、服务端处理类
package com.zx.test;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class SimpleServerHandler extends ChannelInboundHandlerAdapter {
/**
* 本方法用于读取客户端发送的信息
* @param ctx
* @param msg
* @throws Exception
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("SimpleServerHandler.channelRead");
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 = "hello client!";
// 在当前场景下,发送的数据必须转换成ByteBuf数组
ByteBuf encoded = ctx.alloc().buffer(4 * response.length());
encoded.writeBytes(response.getBytes());
ctx.write(encoded);
ctx.flush();
}
/**
* 本方法用作处理异常
* @param ctx
* @param cause
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// 当出现异常就关闭连接
cause.printStackTrace();
ctx.close();
}
/**
* 信息获取完毕后操作
* @param ctx
* @throws Exception
*/
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
}
3、客户端
package com.zx.test;
import io.netty.bootstrap.Bootstrap;
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;
import io.netty.channel.socket.nio.NioSocketChannel;
/**
* 客户端消费者对象
* This is an netty Client
* @author ZX
* @date 2018年6月7日
*/
public class ClientTest {
public void connect(String host, int port) throws Exception {
EventLoopGroup worker = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
/**
*EventLoop的组
*/
b.group(worker);
/**
* 用于构造socketchannel工厂
*/
b.channel(NioSocketChannel.class);
/**设置选项
* 参数:Socket的标准参数(key,value),可自行百度
保持呼吸,不要断气!
* */
b.option(ChannelOption.SO_KEEPALIVE, true);
/**
* 自定义客户端Handle(客户端在这里搞事情)
*/
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new SimpleClientHandler());
}
});
/** 开启客户端监听*/
ChannelFuture f = b.connect(host, port).sync();
/**等待数据直到客户端关闭*/
f.channel().closeFuture().sync();
} finally {
worker.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
ClientTest client=new ClientTest();
client.connect("127.0.0.1", 9999);
}
}
4、客户端处理类
package com.zx.test;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class SimpleClientHandler extends ChannelInboundHandlerAdapter {
/**
* 本方法用于接收服务端发送过来的消息
* @param ctx
* @param msg
* @throws Exception
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("SimpleClientHandler.channelRead");
ByteBuf result = (ByteBuf) msg;
byte[] result1 = new byte[result.readableBytes()];
result.readBytes(result1);
System.out.println("Server said:" + new String(result1));
result.release();
}
/**
* 本方法用于处理异常
* @param ctx
* @param cause
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// 当出现异常就关闭连接
cause.printStackTrace();
ctx.close();
}
/**
* 本方法用于向服务端发送信息
* @param ctx
* @throws Exception
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
String msg = "hello Server!";
ByteBuf encoded = ctx.alloc().buffer(4 * msg.length());
encoded.writeBytes(msg.getBytes());
ctx.write(encoded);
ctx.flush();
}
}
5、运行结果:
服务端:
SimpleServerHandler.channelRead
Client said:hello Server!
客户端:
SimpleClientHandler.channelRead
Server said:hello client!
后话:
好了,看完整篇博文,复制代码,跑起来了!然后你也有了解决问题的思路,不管对错能解决问题了。但是每个对象,每个参数是什么意思能搞懂吗?博主不才,虽然博主后来再次添加了很多注释,但是对很多对象以及参数理解不深,也不知道自己的用法是否是出于设计者本意!
所以,下一篇博主会稍微深入一些介绍对象以及使用,会让你更加了解自己使用的这个NIO中间件工具,若是想成为专家大牛,就自己去下载源码分析吧~博主目前在拓展知识体系阶段,还没有如此多精力去深入,这个需要很多技巧。
废话不多说了,下一篇地址:https://blog.csdn.net/the_fool_/article/details/80623299
【Netty整理01-快速入门】Netty简单使用Demo(已验证)的更多相关文章
- MyBatis 学习总结 01 快速入门
本文测试源码下载地址: http://onl5wa4sd.bkt.clouddn.com/MyBatis0918.rar 一.Mybatis介绍 MyBatis是一个支持普通SQL查询,存储过程和高级 ...
- Spring Boot【快速入门】简单案例
Spring Boot[快速入门] Spring Boot 概述 Build Anything with Spring Boot:Spring Boot is the starting point ...
- Slickflow.NET 开源工作流引擎快速入门之三: 简单或分支流程代码编写示例
前言:对于急切想了解引擎功能的开发人员,在下载版本后,就想尝试编写代码,完成一个流程的开发和测试.本文试图从请假流程,或分支模式来快速了解引擎代码的编写. 1. 创建或分支流程图形 或分支流程是常见的 ...
- Slickflow.NET 开源工作流引擎快速入门之一: 简单序列流程代码编写示例
前言:对于急切想了解引擎功能的开发人员,在下载版本后,就想尝试编写代码,完成一个流程的开发和测试.本文试图从一个最简单的流程来示例说明,如何快速了解引擎代码的编写. 版本: .NETCore 2.1 ...
- awk:快速入门(简单实用19例+鸟哥书内容)
awk 用法:awk ' pattern {action} ' 变量名 含义 ARGC 命令行变元个数 ARGV 命令行变元数组 FILENAME 当前输入文件名 FNR 当前文件中的记录号 ...
- 005 Spark快速入门的简单程序案例
参考:官网的quick start http://spark.apache.org/docs/1.6.0/quick-start.html 这里只是在shell命令行中简单的书写一些命令,做一个简单的 ...
- ❤️❤️爆肝3万字整理小白快速入门分布式版本管理软件:Git,图文并茂(建议收藏)--已码一万字❤️❤️
@ 目录 什么是Git SVN VS Git 什么是版本控制 安装Git 谁在操作? Git本地仓库 本地仓库构造 重点 Git基本操作 git add git commit git diff git ...
- Maven入门指南① :Maven 快速入门及简单使用
原文链接:http://www.cnblogs.com/luotaoyeah/archive/2014/06/02/3764533.html 开发环境 MyEclipse 2014 JDK 1.8 M ...
- Maven 系列 一 :Maven 快速入门及简单使用【转】
开发环境 MyEclipse 2014 JDK 1.8 Maven 3.2.1 1.什么是Maven? Maven是一个项目管理工具,主要用于项目构建,依赖管理,项目信息管理. 2.下载及安装 下载最 ...
随机推荐
- UITextField设置leftView的Insets
Insets就是css中的padding 我们给UITextField设置了leftView,目的是在文本输入框左側显示一个图标.可是在ios7里,这个图标会紧紧地挨着TextField的左边框,非常 ...
- 机器学习: DeepDreaming with TensorFlow (一)
在TensorFlow 的官网上,有一个很有趣的教程,就是用 TensorFlow 以及训练好的深度卷积神经(GoogleNet)网络去生成一些有趣的pattern,通过这些pattern,可以更加深 ...
- sdut 5-1 继承和派生
5-1 继承与派生 Time Limit: 1000MS Memory limit: 65536K 题目描写叙述 通过本题目的练习能够掌握继承与派生的概念.派生类的定义和用法.当中派生类构造函数的定义 ...
- WPF生命周期
App.xaml.cs 重写OnStartup方法,完成初始化 wpf中Window的生命周期
- 线程操纵UI问题
WPF只允许UI线程修改UI,其他线程必须通过Invoke.委托(安全性)Winform可以开启/关闭“只允许UI线程修改UI” 在WPF中非UI线程修改UI的方法 非UI线程直接修改UI,会报错 S ...
- Call asynchronous method in constructor
using System; using System.ComponentModel; using System.Threading.Tasks; public sealed class NotifyT ...
- Aspect Oriented Programming面向切面编程
I简介 Aspect Oriented Programming(AOP),面向切面编程,是一个比较热门的话题.AOP主要实现的目的是针对业务处理过程中的切面进行提取,它所面对的是处理过程中的某个步骤或 ...
- linq中不能准确按拼音排序
在LinqToObject中,利用OrderBy/OrderByDescending, ThenBy/ThenByDescending这4个方法排序时,发现不能正确的按拼音排序,所以在排序时增加编码支 ...
- WPF生成二维码
WPF可以通过ZXing.Net库来实现二维码的功能. 可以通过NuGet安装: Install-Package ZXing.Net 二维码的实现代码: #region 二维码的方法 /// < ...
- MVC4使用SignalR出现$.connection is undefined错误备忘
SignalR使用过程中一定要注意js的引用顺序,否则就会出现$.connection is undefined脚本错误.