im开发总结:netty的使用
最近公司在做一个im群聊的开发,技术使用得非常多,各种代码封装得也是十分优美,使用到了netty,zookeeper,redis,线程池·,mongdb,lua,等系列的技术
netty是对nio的一种封装,很好从效率上解决了,nio的epoll模型的bug问题,那么netty到底是个什么玩意呢:

这个是官网上的一个截图:

大概的意思就是:
Netty是一种NIO客户端服务器框架,它支持网络应用程序(如协议服务器和客户端)的快速和轻松开发。它大大简化和简化了网络编程,如TCP和UDP套接字服务器。“快速和简单”并不意味着最终的应用程序会受到可维护性或性能问题的影响。Netty是根据许多协议(如FTP、SMTP、HTTP以及各种二进制和基于文本的遗留协议)的实现所获得的经验精心设计的。因此,Netty成功地找到了一种在不妥协的情况下实现轻松开发、性能、稳定和灵活性的方法。
那么到底怎么用呢:

我可以看到,userguid部分:
官方推荐使用netty4,netty5已经废弃了,
所以我们可以netty4,进行开发:
首先服务端:
package com.cxy.sever; 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 DiscardServer {
private int port; public DiscardServer(int port) {
this.port = port;
} public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap(); // (2)
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class) // (3)
.childHandler(new ChannelInitializer<SocketChannel>() { // (4)
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new DiscardServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, ) // (5)
.childOption(ChannelOption.SO_KEEPALIVE, true); // (6) // Bind and start to accept incoming connections.
ChannelFuture f = b.bind(port).sync(); // (7) // Wait until the server socket is closed.
// In this example, this does not happen, but you can do that to gracefully
// shut down your server.
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
} public static void main(String[] args) throws Exception {
int port = ;
if (args.length > ) {
port = Integer.parseInt(args[]);
} new DiscardServer(port).run();
}
}
package com.cxy.sever; import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil; public class DiscardServerHandler extends ChannelInboundHandlerAdapter { @Override
public void channelActive(final ChannelHandlerContext ctx) { // (1)
final ByteBuf time = ctx.alloc().buffer(); // (2)
time.writeInt((int) (System.currentTimeMillis() / 1000L + 2208988800L)); final ChannelFuture f = ctx.writeAndFlush(time); // (3)
/*f.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) {
assert f == future;
ctx.close();
}
}); // (4)*/
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2) ByteBuf in = (ByteBuf) msg;
try {
while (in.isReadable()) { // (1)
System.out.print((char) in.readByte());
System.out.flush();
}
} finally {
ReferenceCountUtil.release(msg); // (2)
}
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
// Close the connection when an exception is raised.
cause.printStackTrace();
ctx.close();
} }
客户端
package com.cxy.client; import io.netty.bootstrap.Bootstrap;
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.NioSocketChannel; public class TimeClient {
public static void main(String[] args) throws Exception {
String host = "127.0.0.1";
int port = ;
EventLoopGroup workerGroup = new NioEventLoopGroup(); try {
Bootstrap b = new Bootstrap(); // (1)
b.group(workerGroup); // (2)
b.channel(NioSocketChannel.class); // (3)
b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new TimeClientHandler());
}
}); // Start the client.
ChannelFuture f = b.connect(host, port).sync(); // (5) // Wait until the connection is closed.
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
}
}
}
package com.cxy.client; import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter; import java.util.Date; public class TimeClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf m = (ByteBuf) msg; // (1)
try {
long currentTimeMillis = (m.readUnsignedInt() - 2208988800L) * 1000L;
System.out.println(new Date(currentTimeMillis)); } finally {
m.release();
}
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
整个代码都是官网的上的介绍,拿下来的,所以可以看到,整个基础代码就是那么多:

其中1 是构建服务端
2 初始化socket通道
3添加助手类
4 设置option
5 设置长连接
6 绑定端口
7 关闭channel
8 关闭主从线程池模型

1 创建客户端
2 加入线程池
3 设置长连接
4 绑定相关助手类
5 流水线上添加助手类
6 绑定连接的主机和端口
7 关闭channel
8 关闭工作线程池
可以看出,那么整合netty客户端,服务端的基础代码都是一致的,那么我们使用netty开发需要注意哪些问题呢
我们著需要关闭我们的handler的开发,其他的不用关心。
im开发总结:netty的使用的更多相关文章
- 远程桌面控制项目开发(Spring+Netty+Swing)
[目录] 1.前言 2.初现端倪 3.款款深入 4.责任细分 5.功能层级图 6.项目结构 7.关键类设计 8.一些设计想法 9.待优化 10.一点心得 11.效果演示 12.讨论 13.GitHub ...
- (入门篇 NettyNIO开发指南)第三章-Netty入门应用
作为Netty的第一个应用程序,我们依然以第2章的时间服务器为例进行开发,通过Netty版本的时间服务报的开发,让初学者尽快学到如何搭建Netty开发环境和!运行Netty应用程序. 如果你已经熟悉N ...
- Netty精粹之JAVA NIO开发需要知道的
学习Netty框架以及相关源码也有一小段时间了,恰逢今天除夕,写篇文章总结一下.Netty是个高效的JAVA NIO框架,总体框架基于异步非阻塞的设计,基于网络IO事件驱动,主要贡献在于可以让用户基于 ...
- Netty多协议开发
HTTP协议开发 post与get的区别 1)get用于信息获取,post用于更新资源. 2)get数据放在请求行中,post数据放在请求体内. 3)get对数据长度有限制(2083字节),post没 ...
- Netty 系列之 Netty 高性能之道
1. 背景 1.1. 惊人的性能数据 最近一个圈内朋友通过私信告诉我,通过使用 Netty4 + Thrift 压缩二进制编解码技术,他们实现了 10 W TPS(1 K 的复杂 POJO 对象)的跨 ...
- Java Netty 4.x 用户指南
问题 今天,我们使用通用的应用程序或者类库来实现互相通讯,比如,我们经常使用一个 HTTP 客户端库来从 web 服务器上获取信息,或者通过 web 服务来执行一个远程的调用. 然而,有时候一个通用的 ...
- Netty系列之Netty高性能之道
转载自http://www.infoq.com/cn/articles/netty-high-performance 1. 背景 1.1. 惊人的性能数据 最近一个圈内朋友通过私信告诉我,通过使用Ne ...
- Netty权威指南
Netty权威指南(异步非阻塞通信领域的经典之作,国内首本深入剖析Netty的著作,全面系统讲解原理.实战和源码,带你完美进阶Netty工程师.) 李林锋 著 ISBN 978-7-121-233 ...
- Netty高性能之道
1. 背景 1.1. 惊人的性能数据 最近一个圈内朋友告诉我,通过使用Netty4 + Thrift压缩二进制编解码技术,他们实现了10W TPS(1K的复杂POJO对象)的跨节点远程服务调用.相比于 ...
- 转:Netty系列之Netty高性能之道
1. 背景 1.1. 惊人的性能数据 最近一个圈内朋友通过私信告诉我,通过使用Netty4 + Thrift压缩二进制编解码技术,他们实现了10W TPS(1K的复杂POJO对象)的跨节点远程服务调用 ...
随机推荐
- leetcode.双指针.88合并两个有序数组-Java
1. 具体题目 给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组. 说明: 初始化 nums1 和 nums2 的元素数量分别 ...
- jquery 查找元素,id,class
查找元素下的class 带有.pageactive的a标签 $('a.pageactive') 标签a和..pageactive不要有空格,有空格找不到 ======================= ...
- PHP 算式验证码
这里不多说,直接上代码! /** * 改造的加减法验证类 * 使用示例 VerifyCode::get('xxx', 20); * 验证示例 VerifyCode::check('1', 'xxx') ...
- The Complete Javascript Number Reference 转载自:http://www.hunlock.com/blogs/The_Complete_Javascript_Number_Reference
The Complete Javascript Number Reference Filed: Mon, Apr 30 2007 under Programming|| Tags: reference ...
- hibernate 参数一览
实现包含了Hibernate与数据库的基本连接信息的配置方式有两种方式: 第一种是使用hibernate.properties文件作为配置文件. 第二种是使用hibernate.cfg.xml文件作为 ...
- Winsock编程原理——面向连接
Winsock编程原理——面向连接 Windows Sockets使用套接字进行编程,套接字编程是面向客户端/服务器模型而设计的,因此系统中需要客户端和服务器两个不同类型的进程,根据连接类型的不同,对 ...
- Bata冲刺第三天
这个作业属于哪个课程 https://edu.cnblogs.com/campus/xnsy/SoftwareEngineeringClass2 这个作业要求在哪里 https://edu.cnblo ...
- Java高频经典面试题(第一季)一:自增的分析
package will01; public class testZiZeng { public static void main(String[] args) { int i = 1; i = i ...
- python-django_rest_framework中的request/Response
rest_framework中的request是被rest_framework再次封装过的,并在原request上添加了许多别的属性: (原Django中的request可用request._requ ...
- 转 HTML精确定位:scrollLeft,scrollWidth,clientWidth,offsetWidth之完全详解
HTML:scrollLeft,scrollWidth,clientWidth,offsetWidth到底指的哪到哪的距离之完全详解 scrollHeight: 获取对象的滚动高度. scrollLe ...