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的更多相关文章

  1. Netty 4.0.0.CR6 发布,高性能网络服务框架

    Netty 4.0 发布第 6 个 RC 版本,该版本值得关注的改进有: SslHandler and JZlibEncoder now works correctly. (#1475 and #14 ...

  2. Netty 4.0 新的特性及需要注意的地方

    Netty 4.0 新的特性及需要注意的地方 这篇文章和你一起过下Netty的主发行版本的一些显著的改变和新特性,让你在把你的应用程序转换到新版本的时候有个概念. 项目结构改变 Netty的包名从or ...

  3. [小试牛刀]部署在IDEA的JFinal 3.0 demo

    进入JFinal 极速开发市区:http://www.jfinal.com/ 如上图,点击右边的最新下载:JFinal 3.0 demo - 此过程跳过注册\登录过程, 进入到如下,下载 下载并解压到 ...

  4. Netty心跳简单Demo

    前面简单地了解了一下IdleStateHandler,我们现在写一个简单的心跳demo: 1)服务器端每隔5秒检测服务器端的读超时,如果5秒没有接受到客户端的写请求,也就说服务器端5秒没有收到读事件, ...

  5. netty笔记(一)--Demo

    Netty是一个Java开源框架,用于传输数据.由server和client组成,封装了Java nio,支持TCP, UDP等协议.这里写了一Demo EchoClientHandler.java ...

  6. 【Netty整理01-快速入门】Netty简单使用Demo(已验证)

    多处摘抄或手打,为了十积分厚着脸皮标为原创,惭愧惭愧~本篇文章用于快速入门搭建一个简单的netty 应用,如想稍微深入系统的了解,请参照本人下一篇博客,链接: 参考地址: 官方文档:http://ne ...

  7. Netty的简单Demo

    这个demo是通过网上下载: 使用maven构建的: 项目结构: pom.xml: <dependencies> <dependency> <groupId>io. ...

  8. Spring3.0 demo (注解自动注入)

    这个demo是maven工程,目录结构如下 pom.xml maven依赖 .....省略 <dependency> <groupId>org.springframework& ...

  9. 【Netty学习】Netty 4.0.x版本和Flex 4.6配合

    笔者的男装网店:http://shop101289731.taobao.com .冬装,在寒冷的冬季温暖你.新品上市,环境选购 =================================不华丽 ...

随机推荐

  1. 【转载】Kafka实现篇之消息和日志

    http://blog.csdn.net/honglei915/article/details/37760631 消息格式 日志 一个叫做“my_topic”且有两个分区的的topic,它的日志有两个 ...

  2. (译)如何在ASP.NET中安全使用ViewState

    原文:http://www.codeproject.com/Articles/150688/How-to-make-ViewState-secure-in-ASP-NET 介绍 ASP.NET中的Vi ...

  3. HDOJ2027统计元音

    统计元音 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submis ...

  4. svn 分支整个项目合并主干

    1.首先主干要更新最新版本. 2.找到主干(trunk)点击右键--合并--合并类型选择(合并一个版本范围)点击下一步--合并源选择整个分支项目--将要合并的修改版本范围(选择指定(a)范围)点击下一 ...

  5. Linux命令(4):cat命令

    1.作用:连接并显示指定的一个和多个文件的有关信息: 2.格式:cat [选项] 文件1 文件2 ... 其中文件1.文件2为要显示的多个文件: 3.常见参数: 4.使用实例: [youname@ww ...

  6. error LNK2005: DDX_Control 已经在 uafxcwd.lib(wincore2.obj) 中定义

    编译错误提示: 1>afxnmcdd.lib(wincore2.obj) : error LNK2005: "void __stdcall DDX_Control(classCData ...

  7. Eclipse 调试maven test

    在eclipse中调试maven test 一般情况下,使用如下方式都不能使myeclipse检测到程序中的断点: 项目 -> Run As -> maven test 或 项目 -> ...

  8. 第三十九篇、NavBar动态隐藏、设置透明、毛玻璃效果

    1.动态隐藏 - (void)viewDidLoad { [super viewDidLoad]; if ([self respondsToSelector:@selector(automatical ...

  9. Cocos开发中Visual Studio下libcurl库开发环境设置

    我们介绍一下win32中Visual Studio下libcurl库开发环境设置.Cocos2d-x引擎其实已经带有为Win32下访问libcurl库,Cocos2d-x 3.x中libcurl库文件 ...

  10. UITableView的编辑模式

    UITableView可以分普通模式和Editing模式两种,这里我们着重讨论Editing模式,Editing模式中又分三种操作:Insert.Delete. Reallocted.Insert和D ...