`
liyonghui160com
  • 浏览: 771826 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

netty4.0.23 初学的demo

阅读更多

 

netty4.0.23 初学的demo

 

例子共4个文件,用到的jar包有:

netty-all-4.0.23.Final.jar

log4j.jar (apache的)

commons-logging-1.1.1.jar(apache的)

 

文件 TcpServerHandler

 

Java代码  收藏代码
  1. package test.netty;  
  2.   
  3. import org.apache.log4j.Logger;  
  4.   
  5. import io.netty.channel.ChannelHandlerContext;  
  6. import io.netty.channel.SimpleChannelInboundHandler;  
  7.   
  8. public class TcpServerHandler extends SimpleChannelInboundHandler<Object> {  
  9.   
  10.     private static final Logger logger = Logger.getLogger(TcpServerHandler.class);  
  11.   
  12.     @Override  
  13.     protected void channelRead0(ChannelHandlerContext ctx, Object msg)  
  14.             throws Exception {  
  15.         logger.info("SERVER接收到消息:"+msg);  
  16.         ctx.channel().writeAndFlush("yes, server is accepted you ,nice !"+msg);  
  17.     }  
  18.       
  19.     @Override  
  20.     public void exceptionCaught(ChannelHandlerContext ctx,  
  21.             Throwable cause) throws Exception {  
  22.         logger.warn("Unexpected exception from downstream.", cause);  
  23.         ctx.close();  
  24.     }  
  25.   
  26. }  

 

 

文件 TcpServer

Java代码  收藏代码
  1. package test.netty;  
  2.   
  3. import org.apache.log4j.Logger;  
  4.   
  5. import io.netty.bootstrap.ServerBootstrap;  
  6. import io.netty.channel.ChannelInitializer;  
  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.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 TcpServer {  
  19.   
  20.     private static final Logger logger = Logger.getLogger(TcpServer.class);  
  21.     private static final String IP = "127.0.0.1";  
  22.     private static final int PORT = 9999;  
  23.     /**用于分配处理业务线程的线程组个数 */  
  24.     protected static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors()*2//默认  
  25.     /** 业务出现线程大小*/  
  26.     protected static final int BIZTHREADSIZE = 4;  
  27.         /* 
  28.      * NioEventLoopGroup实际上就是个线程池, 
  29.      * NioEventLoopGroup在后台启动了n个NioEventLoop来处理Channel事件, 
  30.      * 每一个NioEventLoop负责处理m个Channel, 
  31.      * NioEventLoopGroup从NioEventLoop数组里挨个取出NioEventLoop来处理Channel 
  32.      */  
  33.     private static final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);  
  34.     private static final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);  
  35.       
  36.     protected static void run() throws Exception {  
  37.         ServerBootstrap b = new ServerBootstrap();  
  38.         b.group(bossGroup, workerGroup);  
  39.         b.channel(NioServerSocketChannel.class);  
  40.         b.childHandler(new ChannelInitializer<SocketChannel>() {  
  41.             @Override  
  42.             public void initChannel(SocketChannel ch) throws Exception {  
  43.                 ChannelPipeline pipeline = ch.pipeline();  
  44.                 pipeline.addLast("frameDecoder"new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0404));  
  45.                 pipeline.addLast("frameEncoder"new LengthFieldPrepender(4));  
  46.                 pipeline.addLast("decoder"new StringDecoder(CharsetUtil.UTF_8));  
  47.                 pipeline.addLast("encoder"new StringEncoder(CharsetUtil.UTF_8));  
  48.                 pipeline.addLast(new TcpServerHandler());  
  49.             }  
  50.         });  
  51.   
  52.         b.bind(IP, PORT).sync();  
  53.         logger.info("TCP服务器已启动");  
  54.     }  
  55.       
  56.     protected static void shutdown() {  
  57.         workerGroup.shutdownGracefully();  
  58.         bossGroup.shutdownGracefully();  
  59.     }  
  60.   
  61.     public static void main(String[] args) throws Exception {  
  62.         logger.info("开始启动TCP服务器...");  
  63.         TcpServer.run();  
  64. //      TcpServer.shutdown();  
  65.     }  
  66. }  

 

文件 TcpClientHandler

Java代码  收藏代码
  1. package test.netty;  
  2.   
  3. import org.apache.log4j.Logger;  
  4.   
  5. import io.netty.channel.ChannelHandlerContext;  
  6. import io.netty.channel.SimpleChannelInboundHandler;  
  7.   
  8. public class TcpClientHandler extends SimpleChannelInboundHandler<Object> {  
  9.   
  10.     private static final Logger logger = Logger.getLogger(TcpClientHandler.class);  
  11.   
  12.     @Override  
  13.     protected void channelRead0(ChannelHandlerContext ctx, Object msg)  
  14.             throws Exception {  
  15.         //messageReceived方法,名称很别扭,像是一个内部方法.  
  16.         logger.info("client接收到服务器返回的消息:"+msg);  
  17.           
  18.     }  
  19.   
  20. }  

 

文件 TcpClient

Java代码  收藏代码
  1. package test.netty;  
  2.   
  3. import io.netty.bootstrap.Bootstrap;  
  4. import io.netty.channel.Channel;  
  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.nio.NioSocketChannel;  
  11. import io.netty.handler.codec.LengthFieldBasedFrameDecoder;  
  12. import io.netty.handler.codec.LengthFieldPrepender;  
  13. import io.netty.handler.codec.string.StringDecoder;  
  14. import io.netty.handler.codec.string.StringEncoder;  
  15. import io.netty.util.CharsetUtil;  
  16.   
  17. import org.apache.log4j.Logger;  
  18.   
  19. public class TcpClient {  
  20.     private static final Logger logger = Logger.getLogger(TcpClient.class);  
  21.     public static String HOST = "127.0.0.1";  
  22.     public static int PORT = 9999;  
  23.       
  24.     public static Bootstrap bootstrap = getBootstrap();  
  25.     public static Channel channel = getChannel(HOST,PORT);  
  26.     /** 
  27.      * 初始化Bootstrap 
  28.      * @return 
  29.      */  
  30.     public static final Bootstrap getBootstrap(){  
  31.         EventLoopGroup group = new NioEventLoopGroup();  
  32.         Bootstrap b = new Bootstrap();  
  33.         b.group(group).channel(NioSocketChannel.class);  
  34.         b.handler(new ChannelInitializer<Channel>() {  
  35.             @Override  
  36.             protected void initChannel(Channel ch) throws Exception {  
  37.                 ChannelPipeline pipeline = ch.pipeline();  
  38.                 pipeline.addLast("frameDecoder"new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0404));  
  39.                 pipeline.addLast("frameEncoder"new LengthFieldPrepender(4));  
  40.                 pipeline.addLast("decoder"new StringDecoder(CharsetUtil.UTF_8));  
  41.                 pipeline.addLast("encoder"new StringEncoder(CharsetUtil.UTF_8));  
  42.                 pipeline.addLast("handler"new TcpClientHandler());  
  43.             }  
  44.         });  
  45.         b.option(ChannelOption.SO_KEEPALIVE, true);  
  46.         return b;  
  47.     }  
  48.   
  49.     public static final Channel getChannel(String host,int port){  
  50.         Channel channel = null;  
  51.         try {  
  52.             channel = bootstrap.connect(host, port).sync().channel();  
  53.         } catch (Exception e) {  
  54.             logger.error(String.format("连接Server(IP[%s],PORT[%s])失败", host,port),e);  
  55.             return null;  
  56.         }  
  57.         return channel;  
  58.     }  
  59.   
  60.     public static void sendMsg(String msg) throws Exception {  
  61.         if(channel!=null){  
  62.             channel.writeAndFlush(msg).sync();  
  63.         }else{  
  64.             logger.warn("消息发送失败,连接尚未建立!");  
  65.         }  
  66.     }  
  67.   
  68.     public static void main(String[] args) throws Exception {  
  69.         try {  
  70.             long t0 = System.nanoTime();  
  71.             for (int i = 0; i < 100000; i++) {  
  72.                 TcpClient.sendMsg(i+"你好1");  
  73.             }  
  74.             long t1 = System.nanoTime();  
  75.             System.out.println((t1-t0)/1000000.0);  
  76.         } catch (Exception e) {  
  77.             e.printStackTrace();  
  78.         }  
  79.     }  
  80. }  
分享到:
评论

相关推荐

    netty4.0.23final.jar

    netty最新发布jar包,网上很多资料都不能用,这个肯定可以用,我自己已经用了,有问题可以咨询我。

    netty-all-4.0.23.jar

    netty通信所需jar包,最新jar包。个人使用的nettyjar包。

    springboot整合netty的demo

    SpringBoot和Netty都是Java开发领域中的重要工具。SpringBoot以其快速、简洁的特性,极大地简化了Spring应用的初始...通过这个Demo,开发者能够更好地理解和掌握如何在SpringBoot项目中利用Netty实现高性能的网络服务。

    netty简单 的demo很好理解

    这个“netty简单的demo很好理解”的例子,很可能是为了展示Netty的基本用法,帮助初学者理解其核心概念。我们将通过以下几个方面来深入探讨这个Demo: 1. **异步编程模型**: Netty 使用了Java NIO(非阻塞I/O)...

    netty5.0官方自带的demo

    在本文中,我们将深入探讨Netty 5.0官方提供的示例(demo),这些示例是学习和理解Netty核心概念与功能的重要资源。 1. **Netty的异步模型** Netty基于Java NIO(非阻塞I/O)构建,其核心是事件驱动和异步处理。在...

    使用netty的简单demo

    作为一个学Java的,如果没有研究过Netty,那么你对Java语言的使用和理解仅仅停留在表面水平。 如果你想知道Nginx是怎么写出来的,如果你想知道Tomcat和Jetty是如何实现的,如果你也想实现一个简单的Redis服务器,那...

    基于Netty框架的demo项目

    这是一个基于高并发网络框架-Netty框架的demo项目,旨在展示Netty服务端与客户端的基础使用方式,并深入探讨了自定义编解码器以及心跳机制的实现。...无论是Netty初学者还是有一定基础的开发者,都能从中获益匪浅。

    简易版netty websocket通讯demo 聊天

    在本示例中,"简易版netty websocket通讯demo 聊天" 提供了一个基础的 WebSocket 协议通信的实现,用于构建聊天应用。WebSocket 是一种在客户端和服务器之间建立持久连接的协议,它允许双方进行全双工通信,即数据...

    Netty-all-4.0.23.Final.jar

    这个"Netty-all-4.0.23.Final.jar"文件是Netty框架的一个完整集合,包含了4.0.23.Final版本的所有组件和功能。而"netty-3.6.3.Final.jar"则是Netty的3.6.3.Final版本,这两个版本代表了Netty在不同时间点的稳定发布...

    netty同步传输demo

    在“netty同步传输demo”中,我们关注的是如何在Netty中实现客户端的同步调用,以及如何利用ZooKeeper来管理分布式服务端。 首先,让我们深入理解Netty的同步和异步概念。Netty的核心特性之一是其基于NIO(非阻塞I/...

    Netty-SocketIo Demo Chat

    Netty-SocketIo Demo Chat 是一个基于Netty和Socket.IO的实时通信示例,用于实现一个WebChat聊天应用。这个项目结合了Java后端服务和客户端的实时交互,提供了高效、可靠的网络通信解决方案。 首先,Netty是一个高...

    Netty-4.0.23 开发文档(英文原版开发手册)

    Netty-4.0.23 开发文档(英文原版开发手册)

    Netty即时通讯项目Demo

    Netty即时通讯项目Demo是一个基于Netty框架的简单即时通讯应用示例,旨在帮助初学者了解如何利用Netty实现一个基础的群聊功能。Netty是Java领域内一个高性能、异步事件驱动的网络应用程序框架,它极大地简化了网络...

    读书笔记:netty权威指南demo.zip

    读书笔记:netty权威指南demo

    netty4.0.26 英文版 api chm

    Netty 是一个高性能、异步事件驱动的网络应用程序框架,用于快速开发可维护的高性能协议服务器和客户端。这个"Netty4.0.26英文版API CHM"是Netty 4.0.26版本的官方API文档,以CHM(Microsoft编写的帮助文件格式)...

    netty实战教程、netty代码demo

    Netty 是一个高性能、异步事件驱动的网络应用程序框架,用于快速开发可维护的高性能协议服务器和客户端。这个实战教程和代码示例是为那些希望深入理解并运用 Netty 的开发者准备的。以下是对 Netty 的详细介绍以及...

    netty心跳包demo

    这是更具netty的一个demo自己再修改一下 有问题可以联系我

    nettyio-demo.rar

    在这个"NettyIO-Demo"压缩包中,包含了Netty官方的示例代码以及Netty 1.7.19版本的jar包及其所有依赖。这些依赖是运行和学习Netty必不可少的库,它们包括了处理I/O事件、编码解码、协议处理等功能的组件。 Netty ...

    netty及时通讯通讯DEMO

    在"Netty及时通讯通讯DEMO"中,我们可以探讨以下几个关键知识点: 1. **Netty的基本架构**: Netty采用了一种名为“Reactor”模式的设计,该模式分为单线程和多线程两种,用于处理并发连接。其核心组件包括:...

    android+netty 的demo

    这个"android+netty 的demo"可能是为了展示如何在Android应用中集成和使用Netty库。 Netty的核心理念是提供一个高度可定制和易用的网络编程模型,它简化了TCP、UDP以及HTTP等协议的实现。在Android上使用Netty,...

Global site tag (gtag.js) - Google Analytics