使用netty开发简单样例

Netty是什么? 

本质:JBoss做的一个Jar包 

目的:快速开发高性能、高可靠性的网络服务器和客户端程序 

优点:提供异步的、事件驱动的网络应用程序框架和工具 

通俗的说:一个好使的处理Socket的东东 

Netty的特性 

设计 
统一的API,适用于不同的协议(阻塞和非阻塞) 
基于灵活、可扩展的事件驱动模型 
高度可定制的线程模型 
可靠的无连接数据Socket支持(UDP) 

性能 
更好的吞吐量,低延迟 
更省资源 
尽量减少不必要的内存拷贝 

安全 
完整的SSL/TLS和STARTTLS的支持 
能在Applet与Android的限制环境运行良好 

健壮性 
不再因过快、过慢或超负载连接导致OutOfMemoryError 
不再有在高速网络环境下NIO读写频率不一致的问题 

易用 
完善的JavaDoc,用户指南和样例 
简洁简单 

下面提供一个简单的例子 

第一步:下载netty5.0 

移步官网下载 http://netty.io/downloads.html 或者 
使用maven,在pom.xml中添加如下代码 
Java代码   收藏代码
  1. <dependency>  
  2.     <groupId>io.netty</groupId>  
  3.     <artifactId>netty-all</artifactId>  
  4.     <version>5.0.0.Alpha2</version>  
  5. </dependency>  


第二步: 编写Server端代码 

NettyServerBootstrap代码 
Java代码   收藏代码
  1. import java.util.concurrent.TimeUnit;  
  2.   
  3. import org.apache.log4j.Logger;  
  4.   
  5. import io.netty.bootstrap.ServerBootstrap;  
  6. import io.netty.channel.ChannelFuture;  
  7. import io.netty.channel.ChannelInitializer;  
  8. import io.netty.channel.ChannelOption;  
  9. import io.netty.channel.ChannelPipeline;  
  10. import io.netty.channel.EventLoopGroup;  
  11. import io.netty.channel.nio.NioEventLoopGroup;  
  12. import io.netty.channel.socket.SocketChannel;  
  13. import io.netty.channel.socket.nio.NioServerSocketChannel;  
  14. import io.netty.handler.codec.LengthFieldBasedFrameDecoder;  
  15. import io.netty.handler.timeout.IdleStateHandler;  
  16.   
  17. public class NettyServerBootstrap {  
  18.   
  19.     private static Logger logger = Logger.getLogger(NettyServerBootstrap.class);  
  20.   
  21.     private int port;  
  22.   
  23.     public NettyServerBootstrap(int port) {  
  24.         this.port = port;  
  25.         bind();  
  26.     }  
  27.   
  28.     private void bind() {  
  29.   
  30.         EventLoopGroup boss = new NioEventLoopGroup();  
  31.         EventLoopGroup worker = new NioEventLoopGroup();  
  32.   
  33.         try {  
  34.   
  35.             ServerBootstrap bootstrap = new ServerBootstrap();  
  36.   
  37.             bootstrap.group(boss, worker);  
  38.             bootstrap.channel(NioServerSocketChannel.class);  
  39.             bootstrap.option(ChannelOption.SO_BACKLOG, 1024); //连接数  
  40.             bootstrap.option(ChannelOption.TCP_NODELAY, true);  //不延迟,消息立即发送  
  41.             bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); //长连接  
  42.             bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {  
  43.                 @Override  
  44.                 protected void initChannel(SocketChannel socketChannel)  
  45.                         throws Exception {  
  46.                     ChannelPipeline p = socketChannel.pipeline();  
  47.                     p.addLast(new NettyServerHandler());  
  48.                 }  
  49.             });  
  50.             ChannelFuture f = bootstrap.bind(port).sync();  
  51.             if (f.isSuccess()) {  
  52.                 logger.debug("启动Netty服务成功,端口号:" + this.port);  
  53.             }  
  54.             // 关闭连接  
  55.             f.channel().closeFuture().sync();  
  56.   
  57.         } catch (Exception e) {  
  58.             logger.error("启动Netty服务异常,异常信息:" + e.getMessage());  
  59.             e.printStackTrace();  
  60.         } finally {  
  61.             boss.shutdownGracefully();  
  62.             worker.shutdownGracefully();  
  63.         }  
  64.     }  
  65.   
  66. public static void main(String[] args) throws InterruptedException {  
  67.           
  68.         NettyServerBootstrap server= new NettyServerBootstrap(9999);  
  69.   
  70.     }  
  71.   
  72. }  
  

NettyServerHandler代码 
Java代码   收藏代码
  1. import java.io.UnsupportedEncodingException;  
  2.   
  3. import com.datong.base.module.netty.common.Constant;  
  4.   
  5. import io.netty.buffer.ByteBuf;  
  6. import io.netty.buffer.Unpooled;  
  7. import io.netty.channel.ChannelHandlerAdapter;  
  8. import io.netty.channel.ChannelHandlerContext;  
  9.   
  10. public class NettyServerHandler extends ChannelHandlerAdapter {  
  11.   
  12.     @Override  
  13.     public void channelRead(ChannelHandlerContext ctx, Object msg) {  
  14.           
  15.         ByteBuf buf = (ByteBuf) msg;  
  16.           
  17.         String recieved = getMessage(buf);  
  18.         System.out.println("服务器接收到消息:" + recieved);  
  19.           
  20.         try {  
  21.             ctx.writeAndFlush(getSendByteBuf("APPLE"));  
  22.         } catch (UnsupportedEncodingException e) {  
  23.             e.printStackTrace();  
  24.         }  
  25.     }  
  26.   
  27.     /* 
  28.      * 从ByteBuf中获取信息 使用UTF-8编码返回 
  29.      */  
  30.     private String getMessage(ByteBuf buf) {  
  31.   
  32.         byte[] con = new byte[buf.readableBytes()];  
  33.         buf.readBytes(con);  
  34.         try {  
  35.             return new String(con, Constant.UTF8);  
  36.         } catch (UnsupportedEncodingException e) {  
  37.             e.printStackTrace();  
  38.             return null;  
  39.         }  
  40.     }  
  41.       
  42.     private ByteBuf getSendByteBuf(String message)  
  43.             throws UnsupportedEncodingException {  
  44.   
  45.         byte[] req = message.getBytes("UTF-8");  
  46.         ByteBuf pingMessage = Unpooled.buffer();  
  47.         pingMessage.writeBytes(req);  
  48.   
  49.         return pingMessage;  
  50.     }  
  51. }  


第三步:编写Client代码 

NettyClient代码 
Java代码   收藏代码
  1. import java.util.concurrent.TimeUnit;  
  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.EventLoopGroup;  
  8. import io.netty.channel.nio.NioEventLoopGroup;  
  9. import io.netty.channel.socket.SocketChannel;  
  10. import io.netty.channel.socket.nio.NioSocketChannel;  
  11. import io.netty.handler.codec.LengthFieldBasedFrameDecoder;  
  12. import io.netty.handler.timeout.IdleStateHandler;  
  13.   
  14. public class NettyClient {  
  15.   
  16.     /* 
  17.      * 服务器端口号 
  18.      */  
  19.     private int port;  
  20.   
  21.     /* 
  22.      * 服务器IP 
  23.      */  
  24.     private String host;  
  25.   
  26.     public NettyClientBootstrap(int port, String host)  
  27.             throws InterruptedException {  
  28.         this.port = port;  
  29.         this.host = host;  
  30.         start();  
  31.     }  
  32.   
  33.     private void start() throws InterruptedException {  
  34.           
  35.         EventLoopGroup eventLoopGroup = new NioEventLoopGroup();  
  36.           
  37.         try {  
  38.               
  39.             Bootstrap bootstrap = new Bootstrap();  
  40.             bootstrap.channel(NioSocketChannel.class);  
  41.             bootstrap.option(ChannelOption.SO_KEEPALIVE, true);  
  42.             bootstrap.group(eventLoopGroup);  
  43.             bootstrap.remoteAddress(host, port);  
  44.             bootstrap.handler(new ChannelInitializer<SocketChannel>() {  
  45.                 @Override  
  46.                 protected void initChannel(SocketChannel socketChannel)  
  47.                         throws Exception {                    
  48.                     socketChannel.pipeline().addLast(new NettyClientHandler());  
  49.                 }  
  50.             });  
  51.             ChannelFuture future = bootstrap.connect(host, port).sync();  
  52.             if (future.isSuccess()) {  
  53.                 socketChannel = (SocketChannel) future.channel();  
  54.                 System.out.println("----------------connect server success----------------");  
  55.             }  
  56.             future.channel().closeFuture().sync();  
  57.         } finally {  
  58.             eventLoopGroup.shutdownGracefully();  
  59.         }  
  60.     }  
  61.   
  62.     public static void main(String[] args) throws InterruptedException {  
  63.           
  64.         NettyClient client = new NettyClient(9999,  
  65.                 "localhost");  
  66.   
  67.     }  
  68. }  


NettyClientHandler代码 
Java代码   收藏代码
  1. import java.text.SimpleDateFormat;  
  2. import java.util.Date;  
  3. import java.util.concurrent.TimeUnit;  
  4.   
  5. import com.netty.common.NettyStartRunable;  
  6. import com.netty.common.ProxyPool;  
  7. import com.netty.util.JsonUtil;  
  8.   
  9. import net.sf.json.JSONObject;  
  10. import io.netty.buffer.ByteBuf;  
  11. import io.netty.buffer.Unpooled;  
  12. import io.netty.channel.ChannelHandlerAdapter;  
  13. import io.netty.channel.ChannelHandlerContext;  
  14.   
  15. public class NettyClientHandler extends ChannelHandlerAdapter  {  
  16.   
  17.     private  ByteBuf firstMessage;  
  18.       
  19.     @Override  
  20.     public void channelActive(ChannelHandlerContext ctx) throws Exception {  
  21.           
  22.         byte[] data = "服务器,给我一个APPLE".getBytes();  
  23.           
  24.         firstMessage=Unpooled.buffer();  
  25.         firstMessage.writeBytes(data);  
  26.           
  27.         ctx.writeAndFlush(firstMessage);  
  28.     }  
  29.        
  30.     @Override  
  31.     public void channelRead(ChannelHandlerContext ctx, Object msg)  
  32.             throws Exception {  
  33.           
  34.         ByteBuf buf = (ByteBuf) msg;  
  35.       
  36.     String rev = getMessage(bug);  
  37.   
  38.     System.out.println("客户端收到服务器数据:" + rev);  
  39.            
  40.     }  
  41.        
  42.     private String getMessage(ByteBuf buf) {  
  43.   
  44.         byte[] con = new byte[buf.readableBytes()];  
  45.         buf.readBytes(con);  
  46.         try {  
  47.             return new String(con, Constant.UTF8);  
  48.         } catch (UnsupportedEncodingException e) {  
  49.             e.printStackTrace();  
  50.             return null;  
  51.         }  
  52.     }  
  53. }  
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值