最近公司在做一个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的使用的更多相关文章

  1. 远程桌面控制项目开发(Spring+Netty+Swing)

    [目录] 1.前言 2.初现端倪 3.款款深入 4.责任细分 5.功能层级图 6.项目结构 7.关键类设计 8.一些设计想法 9.待优化 10.一点心得 11.效果演示 12.讨论 13.GitHub ...

  2. (入门篇 NettyNIO开发指南)第三章-Netty入门应用

    作为Netty的第一个应用程序,我们依然以第2章的时间服务器为例进行开发,通过Netty版本的时间服务报的开发,让初学者尽快学到如何搭建Netty开发环境和!运行Netty应用程序. 如果你已经熟悉N ...

  3. Netty精粹之JAVA NIO开发需要知道的

    学习Netty框架以及相关源码也有一小段时间了,恰逢今天除夕,写篇文章总结一下.Netty是个高效的JAVA NIO框架,总体框架基于异步非阻塞的设计,基于网络IO事件驱动,主要贡献在于可以让用户基于 ...

  4. Netty多协议开发

    HTTP协议开发 post与get的区别 1)get用于信息获取,post用于更新资源. 2)get数据放在请求行中,post数据放在请求体内. 3)get对数据长度有限制(2083字节),post没 ...

  5. Netty 系列之 Netty 高性能之道

    1. 背景 1.1. 惊人的性能数据 最近一个圈内朋友通过私信告诉我,通过使用 Netty4 + Thrift 压缩二进制编解码技术,他们实现了 10 W TPS(1 K 的复杂 POJO 对象)的跨 ...

  6. Java Netty 4.x 用户指南

    问题 今天,我们使用通用的应用程序或者类库来实现互相通讯,比如,我们经常使用一个 HTTP 客户端库来从 web 服务器上获取信息,或者通过 web 服务来执行一个远程的调用. 然而,有时候一个通用的 ...

  7. Netty系列之Netty高性能之道

    转载自http://www.infoq.com/cn/articles/netty-high-performance 1. 背景 1.1. 惊人的性能数据 最近一个圈内朋友通过私信告诉我,通过使用Ne ...

  8. Netty权威指南

    Netty权威指南(异步非阻塞通信领域的经典之作,国内首本深入剖析Netty的著作,全面系统讲解原理.实战和源码,带你完美进阶Netty工程师.) 李林锋 著   ISBN 978-7-121-233 ...

  9. Netty高性能之道

    1. 背景 1.1. 惊人的性能数据 最近一个圈内朋友告诉我,通过使用Netty4 + Thrift压缩二进制编解码技术,他们实现了10W TPS(1K的复杂POJO对象)的跨节点远程服务调用.相比于 ...

  10. 转:Netty系列之Netty高性能之道

    1. 背景 1.1. 惊人的性能数据 最近一个圈内朋友通过私信告诉我,通过使用Netty4 + Thrift压缩二进制编解码技术,他们实现了10W TPS(1K的复杂POJO对象)的跨节点远程服务调用 ...

随机推荐

  1. 插件化框架解读之Class文件与Dex文件的结构(一)

    阿里P7移动互联网架构师进阶视频(每日更新中)免费学习请点击:https://space.bilibili.com/474380680 Class文件 Class文件是Java虚拟机定义并被其所识别的 ...

  2. 63.Perfect Squares(完美平方数)

    Level:   Medium 题目描述: Given a positive integer n, find the least number of perfect square numbers (f ...

  3. SetViewportOrgEx和SetWindowOrgEx

    在MM_TEXT映射模式下使用这两个函数. 对于 BOOL SetViewportOrgEx( HDC hdc, // 设备内容HANDLE int X, // 新Viewport的x坐标 int Y ...

  4. 钉钉机器人SDK 封装预警消息发送工具

    1 群机器人     (1) 引言     钉钉聊天群内支持的群机器人, 类似QQ 群机器人, 可以发天气, 讲笑话那样;     钉钉群机器人支持自定义机器人, 允许开发者管理机器人做预警消息通知; ...

  5. WPF 的二维绘图(二)——几何图形Geometry

    <本文转自同行> 在WPF的DrawingContext对象中,提供了基本的绘制椭圆和矩形的API:DrawEllipse和DrawRectangle.但是,这些是远远不够用的,我们在日常 ...

  6. 在linux中出现there are stopped jobs 的解决方法【转自:http://www.linuxdiyf.com/viewarticle.php?id=104604】

    在用管理员执行一个命令后,我用Ctrl+Z把命令转移到了后台天.导致我无法退出root的. 输入命令:logout终端显示:There are stopped jobs. 解决方法:输入命令:jobs ...

  7. How can I check the last time stats was run on Oracle without using OEM

    All of the following data dictionary tables have a LAST_ANALYZED column (replace * with USER/ALL/DBA ...

  8. spring 获取url参数

    1. usl格式: http://localhost:8080/contact/delete/3 java代码 @RequestMapping(value="/delete/{id}&quo ...

  9. 05.线程在睡眠时拥有的监视器资源不会被释放(这里使用重入锁ReentrantLock)

    import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public clas ...

  10. 基于Kubernetes 的Cloud Native 实战 培训课程安排

    课程安排: 基于Kubernetes 的Cloud Native 实战 课程介绍: 云计算.虚拟化.容器微服务PaaS 技术已经广泛应用于新兴互联网企业(如电商平台.搜索引擎.社交平台网站.位置服务平 ...