zoukankan      html  css  js  c++  java
  • Netty实例-简单的服务端-client实现,凝视具体

           书籍推荐:                                       实例代码 : http://download.csdn.net/detail/jiangtao_st/7677503

    1. Netty Server端实现
      /**
       * 
       * <p>
       * 	Netty Server Simple
       * </p>
       * 
       * @author 卓轩
       * @创建时间:2014年7月7日
       * @version: V1.0
       */
      
      public class NettyServer {
      	
      	private final int port = 8989;
      	
      	@Test
      	public void nettyServer(){
      		
      		EventLoopGroup bossGroup = new NioEventLoopGroup();
      		EventLoopGroup workerGroup = new NioEventLoopGroup();
      		
      		try {
      			ServerBootstrap serverBootstrap = new ServerBootstrap();
      			serverBootstrap.group(bossGroup,workerGroup)
      				.channel(NioServerSocketChannel.class)
      				.option(ChannelOption.SO_BACKLOG, 1024)
      				.childHandler(new ChildChannelHandler());
      			
      			//绑定端口、同步等待
      			ChannelFuture futrue = serverBootstrap.bind(port).sync();
      			
      			//等待服务监听端口关闭
      			futrue.channel().closeFuture().sync();
      		} catch (InterruptedException e) {
      			// TODO Auto-generated catch block
      			e.printStackTrace();
      		}finally{
      			//退出,释放线程等相关资源
      			bossGroup.shutdownGracefully();
      			workerGroup.shutdownGracefully();
      		}
      
      		
      	}
      
      	private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{
      		@Override
      		protected void initChannel(SocketChannel ch) throws Exception {
      
      			ch.pipeline().addLast(new SimpleServerHandler());
      		}
      	}
      	
      }
      

    2. Netty Client 实现

      /**
       * 
       * <p>
       * 	NettyClient  实现
       * </p>
       * 
       * @author 卓轩
       * @创建时间:2014年7月7日
       * @version: V1.0
       */
      public class NettyClient {
      
      	
      	
      	public void connect(int port,String host){
      		
      		EventLoopGroup group = new NioEventLoopGroup();
      		
      		try {
      			Bootstrap bootstrap = new Bootstrap();
      			bootstrap.group(group)
      			.channel(NioSocketChannel.class)
      			.option(ChannelOption.TCP_NODELAY, true)
      			.handler(new ChannelInitializer<SocketChannel>() {
      
      				@Override
      				protected void initChannel(SocketChannel ch) throws Exception {
      					ch.pipeline().addLast(new SimpleClientHandler());
      				}
      			});
      			//发起异步链接操作
      			ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
      			
      			channelFuture.channel().closeFuture().sync();
      		} catch (InterruptedException e) {
      			// TODO Auto-generated catch block
      			e.printStackTrace();
      		}finally{
      			//关闭,释放线程资源
      			group.shutdownGracefully();
      		}
      	}
      	
      	@Test
      	public void nettyClient(){
      		
      		new NettyClient().connect(8989, "localhost");
      	}
      	
      }


    3. ServerHander 处理程序 

      /**
       * 
       * <p>
       * 	Server接收消息处理Handler
       * </p>
       * 
       * @author 卓轩
       * @创建时间:2014年7月7日
       * @version: V1.0
       */
      public class SimpleServerHandler extends ChannelInboundHandlerAdapter {
      
      	@Override
      	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
      
      		ByteBuf buf = (ByteBuf)msg;
      		byte [] req = new byte[buf.readableBytes()];
      		
      		buf.readBytes(req);
      		
      		String message = new String(req,"UTF-8");
      		
      		System.out.println("Netty-Server:Receive Message,"+ message);
      	
      	}
      }


    4. ClientHander 处理程序

      /**
       * 
       * <p>
       * Client Handler
       * </p>
       * 
       * @author 卓轩
       * @创建时间:2014年7月7日
       * @version: V1.0
       */
      public class SimpleClientHandler extends ChannelInboundHandlerAdapter {
      	
      	private ByteBuf clientMessage;
      	
      
      	public SimpleClientHandler() {
      		
      		byte [] req = "Call-User-Service".getBytes();
      		clientMessage = Unpooled.buffer(req.length);
      		clientMessage.writeBytes(req);
      	}
      
      	@Override
      	public void channelActive(ChannelHandlerContext ctx) throws Exception {
      		
      		ctx.writeAndFlush(clientMessage);
      		
      	}
      
      	@Override
      	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
      		ByteBuf buf = (ByteBuf)msg;
      		byte [] req = new byte[buf.readableBytes()];
      		
      		buf.readBytes(req);
      		
      		String message = new String(req,"UTF-8");
      		
      		System.out.println("Netty-Client:Receive Message,"+ message);
      	}
      
      	@Override
      	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
      
      		ctx.close();
      	}
      }


  • 相关阅读:
    java中Switch的实现原理浅谈
    漫谈计算机编码:从ASCII码到UTF8
    从斐波那契数列看java方法的调用过程
    Java中的位运算及简单的算法应用介绍
    在powserdesigner中,如何将Name(中文注释)导入到sqlserver的字段说明中?
    关于ArcMap的符号库和字体
    ORACLE CHAR,VARCHAR,VARCHAR2,NVARCHAR类型的区别与使用
    在window 2008 上安装arcgisserver93,报arcgissom 密码不符合安全策略
    Power Designer反向数据库时遇到sqlstate=37000错误,解决方案!
    解决PowerDesigner 反向工程没有注释且如何将注释转换成PDM的name
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5238006.html
Copyright © 2011-2022 走看看