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. LeetCode 345

    Reverse Vowels of a String Write a function that takes a string as input and reverse only the vowels ...

  2. 关于在Eclipse中构建patch开发环境

    git仓库中不能添加空文件夹. 至于为什么git 仓库中不能添加空文件夹,我没有找到具体的原因. 在V2EX上有人说: 我猜是因为git的内部实现,即只对文件做快照决定的吧,另一方面空文件夹确实对源代 ...

  3. Scala中的偏函数与部分应用函数

    Scala中有PartialFunction的概念, 同时还要一个概念叫Partial Applied Function. 前者译作偏函数, 后者译作"偏应用函数"或"部 ...

  4. (原创)monitor H3C switch with cacti

    H3C交换机需要做的操作 [H3C]snmp-agent #H3C默认SNMP是关闭的,需要先开启 [H3C]snmp-agent community read public #设置团体名[publi ...

  5. Delphi 获取进程路径及命令行参数

    Delphi 获取进程路径及命令行参数, 但有的进程获取时会报错,不知为啥 type PVOID64 = UINT64; _UNICODE_STRING = packed record Length ...

  6. 开源而又强大的迷你型web服务器推荐

    appweb显然是不二之选,看了下最新版,已经到了4了 下载下来,http://appwebserver.org/software/appweb-4.4.4-0-src.tgz,十几M,直接吓傻,离我 ...

  7. Oracle工程师技能树

    整理了份Oracle工程师的技能树,方便大家在学习的过程中有个大体方向. 欢迎提意见,可以随时更新. 源文件链接地址点此 图片如下: 多媒体插件如下:

  8. Alluxio1.0.1最新版(Tachyon为其前身)介绍,+HDFS分布式环境搭建

    Alluxio(之前名为Tachyon)是世界上第一个以内存为中心的虚拟的分布式存储系统.它统一了数据访问的方式,为上层计算框架和底层存储系统构建了桥梁. 应用只需要连接Alluxio即可访问存储在底 ...

  9. DEDECMS中,引入文件

    引入文件:dede:include 标签:{dede:include filename="foot.htm"/}

  10. 《RedHatLinux逻辑卷的管理》——一条龙服务

    首先建2分区 [root@localhost ~]# partx -d /dev/sdb error deleting partition 4: BLKPG: No such device or ad ...