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端代码:

 1 package netty.test;
2
3
4 import io.netty.bootstrap.ServerBootstrap;
5 import io.netty.channel.Channel;
6 import io.netty.channel.ChannelFuture;
7 import io.netty.channel.ChannelInitializer;
8 import io.netty.channel.ChannelPipeline;
9 import io.netty.channel.EventLoopGroup;
10 import io.netty.channel.nio.NioEventLoopGroup;
11 import io.netty.channel.socket.nio.NioServerSocketChannel;
12 import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
13 import io.netty.handler.codec.LengthFieldPrepender;
14 import io.netty.handler.codec.string.StringDecoder;
15 import io.netty.handler.codec.string.StringEncoder;
16 import io.netty.util.CharsetUtil;
17
18 public class MyNettyServer {
19 private static final String IP = "127.0.0.1";
20 private static final int PORT = 5656;
21 private static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors()*2;
22
23 private static final int BIZTHREADSIZE = 100;
24 private static final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);
25 private static final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);
26 public static void service() throws Exception {
27 ServerBootstrap bootstrap = new ServerBootstrap();
28 bootstrap.group(bossGroup, workerGroup);
29 bootstrap.channel(NioServerSocketChannel.class);
30 bootstrap.childHandler(new ChannelInitializer<Channel>() {
31
32 @Override
33 protected void initChannel(Channel ch) throws Exception {
34 // TODO Auto-generated method stub
35 ChannelPipeline pipeline = ch.pipeline();
36 pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
37 pipeline.addLast(new LengthFieldPrepender(4));
38 pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
39 pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
40 pipeline.addLast(new TcpServerHandler());
41 }
42
43 });
44 ChannelFuture f = bootstrap.bind(IP, PORT).sync();
45 f.channel().closeFuture().sync();
46 System.out.println("TCP服务器已启动");
47 }
48
49 protected static void shutdown() {
50 workerGroup.shutdownGracefully();
51 bossGroup.shutdownGracefully();
52 }
53
54 public static void main(String[] args) throws Exception {
55 System.out.println("开始启动TCP服务器...");
56 MyNettyServer.service();
57 // HelloServer.shutdown();
58 }
59 }

对应的Handler对象 TcpServerHandler.java

 1 package netty.test;
2
3 import io.netty.channel.ChannelHandlerAdapter;
4 import io.netty.channel.ChannelHandlerContext;
5 import io.netty.channel.ChannelInboundHandlerAdapter;
6
7 public class TcpServerHandler extends ChannelInboundHandlerAdapter {
8
9
10 @Override
11 public void channelRead(ChannelHandlerContext ctx, Object msg)
12 throws Exception {
13 // TODO Auto-generated method stub
14 System.out.println("server receive message :"+ msg);
15 ctx.channel().writeAndFlush("yes server already accept your message" + msg);
16 ctx.close();
17 }
18 @Override
19 public void channelActive(ChannelHandlerContext ctx) throws Exception {
20 // TODO Auto-generated method stub
21 System.out.println("channelActive>>>>>>>>");
22 }
23 @Override
24 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
25 System.out.println("exception is general");
26 }
27 }

客户端代码:

 1 package netty.test;
2
3 import io.netty.bootstrap.Bootstrap;
4 import io.netty.channel.ChannelFuture;
5 import io.netty.channel.ChannelInitializer;
6 import io.netty.channel.ChannelOption;
7 import io.netty.channel.ChannelPipeline;
8 import io.netty.channel.EventLoopGroup;
9 import io.netty.channel.nio.NioEventLoopGroup;
10 import io.netty.channel.socket.SocketChannel;
11 import io.netty.channel.socket.nio.NioSocketChannel;
12 import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
13 import io.netty.handler.codec.LengthFieldPrepender;
14 import io.netty.handler.codec.string.StringDecoder;
15 import io.netty.handler.codec.string.StringEncoder;
16 import io.netty.util.CharsetUtil;
17
18 public class NettyClient implements Runnable {
19
20 @Override
21 public void run() {
22 EventLoopGroup group = new NioEventLoopGroup();
23 try {
24 Bootstrap b = new Bootstrap();
25 b.group(group);
26 b.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true);
27 b.handler(new ChannelInitializer<SocketChannel>() {
28 @Override
29 protected void initChannel(SocketChannel ch) throws Exception {
30 ChannelPipeline pipeline = ch.pipeline();
31 pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
32 pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
33 pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
34 pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
35
36 pipeline.addLast("handler", new HelloClient());
37 }
38 });
39 for (int i = 0; i < 100000; i++) {
40 ChannelFuture f = b.connect("127.0.0.1", 5656).sync();
41 f.channel().writeAndFlush("hello Service!"+Thread.currentThread().getName()+":--->:"+i);
42 f.channel().closeFuture().sync();
43 }
44
45
46 } catch (Exception e) {
47
48 } finally {
49 group.shutdownGracefully();
50 }
51 }
52
53 public static void main(String[] args) throws Exception {
54 for (int i = 0; i < 1000; i++) {
55 new Thread(new NettyClient(),">>>this thread "+i).start();
56 }
57 }
58 }

客户端对应的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 demo的更多相关文章

  1. 基于websocket的netty demo

    前面2文 基于http的netty demo 基于socket的netty demo 讲了netty在http和socket的使用,下面讲讲netty如何使用websocket websocket是h ...

  2. 基于socket的netty demo

    前面一文说了 基于http的netty demo 和http不一样,http可以用浏览器来充当客户端调用,所以基于socket的netty,必须要编写客户端和服务器的代码 实现功能: 客户端给服务器发 ...

  3. Java NIO框架Netty demo

    Netty是什么 Netty是一个java开源框架.Netty提供异步的.事件驱动的网络应用程序框架和工具,用以快速开发高性能.高可靠性的网络服务器和客户端程序. 也就是说,Netty 是一个基于NI ...

  4. 基于http的netty demo

    1.引入netty的pom <dependency> <groupId>io.netty</groupId> <artifactId>netty-all ...

  5. Java Netty 4.x 用户指南

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

  6. netty心跳机制测试

    netty中有比较完善的心跳机制,(在基础server版本基础上[netty基础--基本收发])添加少量代码即可实现对心跳的监测和处理. 1 server端channel中加入心跳处理机制 // Id ...

  7. Netty4 学习笔记之二:客户端与服务端心跳 demo

    前言 在上一篇Netty demo 中,了解了Netty中的客户端和服务端之间的通信.这篇则介绍Netty中的心跳. 之前在Mina 中心跳的使用是通过继承 KeepAliveMessageFacto ...

  8. Netty1:初识Netty

    为什么使用Netty Netty是业界最流行的NIO框架之一,它的健壮性.功能.性能.可定制性.可扩展性在同类框架中都是首屈一指的,它已经得到了成百上千的商用项目的证明.对于为什么使用Netty这个话 ...

  9. Netty学习笔记(六) 简单的聊天室功能之WebSocket客户端开发实例

    在之前的Netty相关学习笔记中,学习了如何去实现聊天室的服务段,这里我们来实现聊天室的客户端,聊天室的客户端使用的是Html5和WebSocket实现,下面我们继续学习. 创建客户端 接着第五个笔记 ...

随机推荐

  1. Unity 关于属性的get/set

    学习Unity的可能多数是C#转过来的, 一进来的时候你会发现Unity编写代码,在一些视频或文章中.基本都没有用过get/set使用, 多数是public string name;这样写的公开字段, ...

  2. nand烧写分析/内核在启动过程中式如何将这个文件映射成/目录及各子目录的?

    我用的是ramdisk.image.gz,烧写在flash的0x10140000处 我不太明白内核在启动过程中式如何将这个文件映射成/目录及各子目录的? 如果ramdisk.image.gz在flas ...

  3. LR实战之Discuz开源论坛——安装及简介

    想了很久,也许是因为这段时间特别闲,从毕业到现在,我的测试职业生涯也近两年了,发现自己越来越喜欢测试领域,也越来越偏向测试开发了,作为一名专业的测试人员,不得不要学习性能测试,而使用LoadRunne ...

  4. 在unity的scene中画五角星

    使用Gizmos的DrawLine方法画线. 首先在场景中找到五角星的五个定点的坐标,按照一笔画的顺序命名为1,2,3,4,5,如图所示: 接下来就是编写代码了,代码很少,如下所示: using Un ...

  5. 【欧拉函数】【HDU1286】 找新朋友

    找新朋友 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submi ...

  6. ASP.NET实现图片防盗链(转)

    使用httpHandle来实现,对图片文件的请求做专门的处理第一步:创建一个类,继承自IHttpHandler,代码如下 C# code using System; using System.Web; ...

  7. global中拦截404错误的实现方法

    1. void Application_Error(object sender, EventArgs e) { if(Context != null) { HttpContext ctx = Http ...

  8. 单链表(Single Linked List)

    链表的结点结构  ┌───┬───┐  │data|next│  └───┴───┘ data域--存放结点值的数据域 next域--存放结点的直接后继的地址(位置)的指针域(链域) 实例:从终端输入 ...

  9. jdbc 日期 时间

    //pstmt.setDate(1, new Date(new java.util.Date().getTime())); pstmt.setTime(1, new Time(new java.uti ...

  10. 2Sum,3Sum,4Sum,kSum,3Sum Closest系列

    1).2sum 1.题意:找出数组中和为target的所有数对 2.思路:排序数组,然后用两个指针i.j,一前一后,计算两个指针所指内容的和与target的关系,如果小于target,i右移,如果大于 ...