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对象)的跨节点远程服务调用 ...
随机推荐
- 服务器oracle数据库定时备份
首先要先建立一个.bat的文件 然后执行这个bat文件 测试是否能得到这个收据库的打包文件. bat文件内容: @echo off@color bdel /f /s /q D:\oracle\bac ...
- Pycharm2019版官方版本激活码,无需破解
AHD9079DKZ-eyJsaWNlbnNlSWQiOiJBSEQ5MDc5REtaIiwibGljZW5zZWVOYW1lIjoiSmV0IEdyb3VwcyIsImFzc2lnbmVlTmFtZ ...
- 44-python基础-python3-字符串-常用字符串方法(二)-isalpha()-isalnum()-isdigit()-isspace()-istitle()
3-isX 字符串方法 序号 方法 条件 返回结果1 返回结果2 1 isalpha() 如果字符串只包含字母,并且非空; True False 2 isalnum() 如果字符串只包含字母和数字 ...
- addr2line探秘 [從ip讀出程式中哪行出錯]
addr2line探秘 在Linux下写C/C++程序的程序员,时常与Core Dump相见.在内存越界访问,收到不能处理的信号,除零等错误出现时,我们精心或不精心写就的程序就直接一命呜呼了,Core ...
- HDU 3571 N-dimensional Sphere( 高斯消元+ 同余 )
N-dimensional Sphere Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Oth ...
- java虚拟机规范(se8)——class文件格式(七)
4.7.5 Exceptions 属性 Exceptions 属性是一个变长属性,它位于 method_info(§4.6)结构的属性表中. Exceptions 属性指出了一个方法需要检查的可能抛出 ...
- 任正非:5G技术只独家卖给美国!不卖给韩国、日本、欧洲
https://v.qq.com/x/page/g3001d0xvxe.html 我只转个标题,细节不管了. 呃,实际上就是说,老任头也决定向美国低头了,对不. 不过,也确实没办法. 该起床吃钙片了.
- getopts举例
- jQuery HTML-删除元素
html <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <ti ...
- 图解SSH原理_20190613
SSH仅仅是一协议标准,其具体的实现有很多,既有开源实现的OpenSSH,也有商业实现方案.使用范围最广泛的当然是开源实现OpenSSH. 2. SSH工作原理 在讨论SSH的原理和使用前,我们需要分 ...