Netty是什么?
本质:JBoss做的一个Jar包
目的:快速开发高性能、高可靠性的网络服务器和客户端程序
优点:提供异步的、事件驱动的网络应用程序框架和工具
通俗的说:一个好使的处理Socket的东东
Netty的特性
设计
统一的API,适用于不同的协议(阻塞和非阻塞)
基于灵活、可扩展的事件驱动模型
高度可定制的线程模型
可靠的无连接数据Socket支持(UDP)
性能
更好的吞吐量,低延迟
更省资源
尽量减少不必要的内存拷贝
安全
完整的SSL/TLS和STARTTLS的支持
能在Applet与Android的限制环境运行良好
健壮性
不再因过快、过慢或超负载连接导致OutOfMemoryError
不再有在高速网络环境下NIO读写频率不一致的问题
易用
完善的JavaDoc,用户指南和样例
简洁简单
下面提供一个简单的例子
第一步:下载netty5.0
移步官网下载
http://netty.io/downloads.html或者
使用maven,在pom.xml中添加如下代码
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>5.0.0.Alpha2</version>
</dependency>
第二步: 编写Server端代码
NettyServerBootstrap代码
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
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.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
public class NettyServerBootstrap {
private static Logger logger = Logger.getLogger(NettyServerBootstrap.class);
private int port;
public NettyServerBootstrap(int port) {
this.port = port;
bind();
}
private void bind() {
EventLoopGroup boss = new NioEventLoopGroup();
EventLoopGroup worker = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(boss, worker);
bootstrap.channel(NioServerSocketChannel.class);
bootstrap.option(ChannelOption.SO_BACKLOG, 1024); //连接数
bootstrap.option(ChannelOption.TCP_NODELAY, true); //不延迟,消息立即发送
bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); //长连接
bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel)
throws Exception {
ChannelPipeline p = socketChannel.pipeline();
p.addLast(new NettyServerHandler());
}
});
ChannelFuture f = bootstrap.bind(port).sync();
if (f.isSuccess()) {
logger.debug("启动Netty服务成功,端口号:" + this.port);
}
// 关闭连接
f.channel().closeFuture().sync();
} catch (Exception e) {
logger.error("启动Netty服务异常,异常信息:" + e.getMessage());
e.printStackTrace();
} finally {
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException {
NettyServerBootstrap server= new NettyServerBootstrap(9999);
}
}
NettyServerHandler代码
import java.io.UnsupportedEncodingException;
import com.datong.base.module.netty.common.Constant;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
public class NettyServerHandler extends ChannelHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf buf = (ByteBuf) msg;
String recieved = getMessage(buf);
System.out.println("服务器接收到消息:" + recieved);
try {
ctx.writeAndFlush(getSendByteBuf("APPLE"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/*
* 从ByteBuf中获取信息 使用UTF-8编码返回
*/
private String getMessage(ByteBuf buf) {
byte[] con = new byte[buf.readableBytes()];
buf.readBytes(con);
try {
return new String(con, Constant.UTF8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
private ByteBuf getSendByteBuf(String message)
throws UnsupportedEncodingException {
byte[] req = message.getBytes("UTF-8");
ByteBuf pingMessage = Unpooled.buffer();
pingMessage.writeBytes(req);
return pingMessage;
}
}
第三步:编写Client代码
NettyClient代码
import java.util.concurrent.TimeUnit;
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;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
public class NettyClient {
/*
* 服务器端口号
*/
private int port;
/*
* 服务器IP
*/
private String host;
public NettyClientBootstrap(int port, String host)
throws InterruptedException {
this.port = port;
this.host = host;
start();
}
private void start() throws InterruptedException {
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
bootstrap.group(eventLoopGroup);
bootstrap.remoteAddress(host, port);
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel)
throws Exception {
socketChannel.pipeline().addLast(new NettyClientHandler());
}
});
ChannelFuture future = bootstrap.connect(host, port).sync();
if (future.isSuccess()) {
socketChannel = (SocketChannel) future.channel();
System.out.println("----------------connect server success----------------");
}
future.channel().closeFuture().sync();
} finally {
eventLoopGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException {
NettyClient client = new NettyClient(9999,
"localhost");
}
}
NettyClientHandler代码
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import com.netty.common.NettyStartRunable;
import com.netty.common.ProxyPool;
import com.netty.util.JsonUtil;
import net.sf.json.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
public class NettyClientHandler extends ChannelHandlerAdapter {
private ByteBuf firstMessage;
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
byte[] data = "服务器,给我一个APPLE".getBytes();
firstMessage=Unpooled.buffer();
firstMessage.writeBytes(data);
ctx.writeAndFlush(firstMessage);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
ByteBuf buf = (ByteBuf) msg;
String rev = getMessage(bug);
System.out.println("客户端收到服务器数据:" + rev);
}
private String getMessage(ByteBuf buf) {
byte[] con = new byte[buf.readableBytes()];
buf.readBytes(con);
try {
return new String(con, Constant.UTF8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
}
分享到:
相关推荐
Netty5.0jar包带javadoc Netty4.03API文档CHM格式
官方自带的netty5.0案例,非常强大,学习netty必备!
Netty 入门与实战:仿写微信 IM 即时通讯系统
netty5.0架构剖析和源码解读, 很清楚的讲解了netty5.0的架构和源码
Netty5.0架构剖析和源码解读,学习NIO,学习netty,值得学习
采用Netty5.0编的的TCP/IP上传文件的列子,实现了拆包,合并
《Netty进阶之路:跟着案例学Netty》中的案例涵盖了Netty...在案例的分析过程中,还穿插讲解了Netty的问题定位思路、方法、技巧,以及解决问题使用的相关工具,对读者在实际工作中用好Netty具有很大的帮助和启发作用。
传统BIO通信的弊端 在JDK 1.4推出JAVANIO1.0之前,基于JAVA 的所有Socket通信都采用 BIO 了同步阻塞模式( ),这种一请求一应答的通信模型简化了上层的应用开发, 但是在可靠性和性能方面存在巨大的弊端。...
Netty 5.0.0.Alpha1 版本,包含:Jar包+源代码+API文档。 官网Netty 5.0版本已经废弃,所以发布出来,方便大家下载。 《Netty权威指南》一书使用的就是Netty 5.0
服务器条件NETTY框架编程: 服务器IP:192.168.2.106 端口8810 数据传输的方式:从串口接收到一条完整的协议数据,计算出数据字节长度,打包成HtAlingProtocol类,并发送给服务器; package ...
Netty 5.0.0.Alpha2 版本,包含:Jar包+源代码+API文档。 官网Netty 5.0版本已经废弃,所以发布出来,方便大家下载。 《Netty权威指南》一书使用的就是Netty 5.0
Netty5.0架构剖析和源码解读.pdf是一本比较全的讲解netty5的书籍,任何对java的nio技术感兴趣的人都值得一看。
netty5.0通信框架实现客户端和服务器端demo 的数据对象传输,控制的比较完美,里面包括了netty5.0通信框架jar包
Netty5.0架构剖析和源码解读 目录 1. 概述 2. NIO 入门 3. Netty 源码分析 4. Netty 架构 5. 附录
Netty 入门与实战:仿写微信 IM 即时通讯系统
Netty5.0架构剖析和源码解读 李林峰 可编辑文字版.pdf
netty5.0jar包netty-all-5.0.0.Alpha2,用于开发netty服务器
netty5.0.jar 用于java之间的通信 也可以与其他语言通信 利用Handler就行
8.实战:Netty实现客户端登录 15 9.实战:实现客户端与服务端收发消息 16 10.Pipeline与ChannelHandler 17 11.实战:构建客户端与服务端 Pipeline 18 12.实战:拆包粘包理论与解决方案 20 13.ChannelHandler的生命周期 ...