Netty 4.0 demo
netty是一个异步,事件驱动的网络编程框架&工具,使用netty,可以快速开发从可维护,高性能的协议服务和客户端应用。是一个继mina之后,一个非常受欢迎的nio网络框架
netty4.x和之前的版本变化很大,包结构、对象和之前有很大不同。原来的包结构都是org.jboss.netty.*;目前改为了io.netty.* 的方式,其中,server,client的对象也和原来不同了
根据4.x的稳定版本4.0.14为蓝本,写一个hello world试试看。值得注意的是,4.0.x的beta版和final版本也有不小调整。很不幸的时,在4.x中刚出现的部分方法,到5.x中也将废弃。哎,苦逼的IT人。废话不说,看个4.x的例子吧
需要说明的是,我用的是netty4.0.13这个版本。因为netty有很多包,大家可以引入这个all包,其他的就全部包括了。
server端代码:
package netty.test; import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil; public class MyNettyServer {
private static final String IP = "127.0.0.1";
private static final int PORT = 5656;
private static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors()*2; private static final int BIZTHREADSIZE = 100;
private static final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);
private static final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);
public static void service() throws Exception {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup);
bootstrap.channel(NioServerSocketChannel.class);
bootstrap.childHandler(new ChannelInitializer<Channel>() { @Override
protected void initChannel(Channel ch) throws Exception {
// TODO Auto-generated method stub
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
pipeline.addLast(new LengthFieldPrepender(4));
pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast(new TcpServerHandler());
} });
ChannelFuture f = bootstrap.bind(IP, PORT).sync();
f.channel().closeFuture().sync();
System.out.println("TCP服务器已启动");
} protected static void shutdown() {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
} public static void main(String[] args) throws Exception {
System.out.println("开始启动TCP服务器...");
MyNettyServer.service();
// HelloServer.shutdown();
}
}
对应的Handler对象 TcpServerHandler.java
package netty.test; import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter; public class TcpServerHandler extends ChannelInboundHandlerAdapter { @Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
// TODO Auto-generated method stub
System.out.println("server receive message :"+ msg);
ctx.channel().writeAndFlush("yes server already accept your message" + msg);
ctx.close();
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
System.out.println("channelActive>>>>>>>>");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("exception is general");
}
}
客户端代码:
package netty.test; import io.netty.bootstrap.Bootstrap;
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.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil; public class NettyClient implements Runnable { @Override
public void run() {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group);
b.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8)); pipeline.addLast("handler", new HelloClient());
}
});
for (int i = 0; i < 100000; i++) {
ChannelFuture f = b.connect("127.0.0.1", 5656).sync();
f.channel().writeAndFlush("hello Service!"+Thread.currentThread().getName()+":--->:"+i);
f.channel().closeFuture().sync();
} } catch (Exception e) { } finally {
group.shutdownGracefully();
}
} public static void main(String[] args) throws Exception {
for (int i = 0; i < 1000; i++) {
new Thread(new NettyClient(),">>>this thread "+i).start();
}
}
}
客户端对应的Handler对象代码,HelloClient.java
package netty.test; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter; public class HelloClient extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("client接收到服务器返回的消息:" + msg);
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("client exception is general");
}
}
Netty 4.0 demo的更多相关文章
- Netty 4.0.0.CR6 发布,高性能网络服务框架
Netty 4.0 发布第 6 个 RC 版本,该版本值得关注的改进有: SslHandler and JZlibEncoder now works correctly. (#1475 and #14 ...
- Netty 4.0 新的特性及需要注意的地方
Netty 4.0 新的特性及需要注意的地方 这篇文章和你一起过下Netty的主发行版本的一些显著的改变和新特性,让你在把你的应用程序转换到新版本的时候有个概念. 项目结构改变 Netty的包名从or ...
- [小试牛刀]部署在IDEA的JFinal 3.0 demo
进入JFinal 极速开发市区:http://www.jfinal.com/ 如上图,点击右边的最新下载:JFinal 3.0 demo - 此过程跳过注册\登录过程, 进入到如下,下载 下载并解压到 ...
- Netty心跳简单Demo
前面简单地了解了一下IdleStateHandler,我们现在写一个简单的心跳demo: 1)服务器端每隔5秒检测服务器端的读超时,如果5秒没有接受到客户端的写请求,也就说服务器端5秒没有收到读事件, ...
- netty笔记(一)--Demo
Netty是一个Java开源框架,用于传输数据.由server和client组成,封装了Java nio,支持TCP, UDP等协议.这里写了一Demo EchoClientHandler.java ...
- 【Netty整理01-快速入门】Netty简单使用Demo(已验证)
多处摘抄或手打,为了十积分厚着脸皮标为原创,惭愧惭愧~本篇文章用于快速入门搭建一个简单的netty 应用,如想稍微深入系统的了解,请参照本人下一篇博客,链接: 参考地址: 官方文档:http://ne ...
- Netty的简单Demo
这个demo是通过网上下载: 使用maven构建的: 项目结构: pom.xml: <dependencies> <dependency> <groupId>io. ...
- Spring3.0 demo (注解自动注入)
这个demo是maven工程,目录结构如下 pom.xml maven依赖 .....省略 <dependency> <groupId>org.springframework& ...
- 【Netty学习】Netty 4.0.x版本和Flex 4.6配合
笔者的男装网店:http://shop101289731.taobao.com .冬装,在寒冷的冬季温暖你.新品上市,环境选购 =================================不华丽 ...
随机推荐
- 关于JDK中的集合总结(一)
静态方法只能继承,不能重写(Override). StringBufffer,数组,对象 都是容器. 加入数据,“zhangsan” true ,67, 三个数据数据类型不同,不能用数组作为集合,只能 ...
- 逆向+两次bfs(UVA 1599)
为什么都说简单好想咧.坦白从宽看了人家的代码,涨了好多姿势,, http://blog.csdn.net/u013382399/article/details/38227917 被一个细节坑了.. 2 ...
- Netbackup磁带过期处理
bpexpdate -m <mediaid> -d 0 如果不通过,看是否被其他media server写入数据.使用 nbemmcmd -listhost 查看所有media serve ...
- 用Activator.CreateInstance代替new实现类的实例化(转)
一直想得到这样一个函数,输入一个类的名称为参数,返回一个相应的类的实例. 这在工厂模式中是非常有用的 这样,可以使程序有更高的扩展性,例如,,下面的例子 如果现在有一个类,专门用来计算交通工具的速度, ...
- java下实现调用oracle的存储过程和函数
在Oracle下创建一个test的账户,然后 1.创建表:STOCK_PRICES --创建表格 CREATE TABLE STOCK_PRICES( RIC VARCHAR() PRIMARY KE ...
- 【网络收集】数据库中字段类型对应C#中的数据类型
数据库中字段类型对应C#中的数据类型: 数据库 C#程序 int int32 text string bigint int64 binary System.Byte[] bit Boolean cha ...
- JSP之初识2
<与%之间不可有空格,但是后面可以有空格 <%@ page language="java" import="java.util.*" pageEnc ...
- 【Android学习】自定义Android样式checkbox
下面简单介绍下在Androdi中如何更改Checkbox的背景图片,可以自定义样式 1.首先res/drawable中定义编写如下样式的XML,命名为:checkbox_style: <?xml ...
- JS正则与.net正则表达式的区别
原字符串:长期投资人月井石问华菱钢铁(000932)公司反复强调VAMA的战略意义,请问在2015年4季度达产后对公司贡献的盈利预期 正则匹配处理后:公司反复强调VAMA的战略意义,请问在2015年4 ...
- ###《VIM实用技巧》
###<VIM实用技巧> #@author: gr #@date: 2015-11-20 #@email: forgerui@gmail.com <VIM实用技巧>阅读笔记. ...