zoukankan      html  css  js  c++  java
  • Netty实现Tcp客户端

    1、client类  建立socket连接,发送报文请求服务端

    package com.bokeyuan.client;
    
    import io.netty.bootstrap.Bootstrap;
    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.ChannelOption;
    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.string.StringDecoder;
    import io.netty.handler.codec.string.StringEncoder;
    import java.nio.charset.Charset;
    
    public class Client {
    
       
       public static void main(String[] args) {
          /**调用netty客户端*/
          doRequest();
       }
    
       private static void doRequest(){
          /**处理请求和服务端响应数据的线程组*/
          EventLoopGroup workerGroup = new NioEventLoopGroup();
          try {
             /**客户端相关配置信息*/
             Bootstrap bootstrap = new Bootstrap();
             //绑定线程组
             bootstrap.group(workerGroup);
             bootstrap.channel(NioSocketChannel.class);
             bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
             /*
              * 客户端必须绑定处理器,也就是必须调用handler方法
              */
             bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                   ch.pipeline().addLast(new ClientHandler());
                }
             });
    
             ChannelFuture future = bootstrap.connect("192.169.1.165", 8091).sync();
             //请求报文
             String msg="0010awesdfgtyh";
             byte[] data = msg.getBytes("GBK");
             ByteBuf byteBufMsg = Unpooled.buffer();
             byteBufMsg.writeBytes(data);
             future.channel().writeAndFlush(byteBufMsg);
    future.channel().closeFuture().sync(); }
    catch (InterruptedException e) { e.printStackTrace(); }finally{ workerGroup.shutdownGracefully(); } } }

    2、ClientHandler 处理服务端响应报文

     继承ChannelInboundHandlerAdapter 类

    package com.bokeyuan.client;
    
    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;
    
    import java.io.UnsupportedEncodingException;
    
    
    
    public class ClientHandler extends ChannelInboundHandlerAdapter {
    
       @Override
       public void channelRead(ChannelHandlerContext ctx, Object msg)
             throws Exception {
          try{
             ByteBuf buf = (ByteBuf) msg;
             String rev = getMessage(buf);
             System.out.println("响应报文:" + rev);
          }catch (Exception e){
             e.printStackTrace();
          }
    
       }
    
       private String getMessage(ByteBuf buf) {
          byte[] con = new byte[buf.readableBytes()];
          buf.readBytes(con);
          try {
             return new String(con, "GBK");
          } catch (UnsupportedEncodingException e) {
             e.printStackTrace();
             return null;
          }
       }
    }

    其他写法

    1、改成在ClientHandler类(继承了ChannelInboundHandlerAdapter)中发送请求报文

    • 1、覆写父类channelActive方法,在此方法中调用ctx.writeAndFlush()发送请求报文

      (客户端与服务端建立连接时会执行channelActive方法)

       

    •  2、去掉Client类中的future.channel().wirteAndFlush()代码

       

     

    2、直接传报文字符串,不将报文转为ByteBuf,即channel.writeAndFlush(报文字符串)

    •  1.1、innitChannel中添加字符串解码器,字符串编码器
    •  1.2、future.channel().writeAndFlush(msg)中 ,msg直接传原始报文内容,不需要转为ByteBuf

      

    •  1.3、ClientHandler类的channelRead方法,不需要将msg由Bytebuf转为String

       

     

    作者:小念
    本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。
  • 相关阅读:
    自己写的杨辉三角打印算法
    linux下将编译错误输出到一个文本文件
    在重命名SqlServer数据库时,报5030错误的解决办法
    将毫秒数转换为时分秒
    搜索手机中的所有音频文件
    安卓-去除ActionBar的方法
    Android, JSONLIB , java.lang.NoClassDefFoundError: Failed resolution of: Lnet/sf/json/JSONArray; 原因
    安卓开发错误:The type android.support.v4.app.TaskStackBuilder$SupportParentable cannot be resolved.
    Jar mismatch! Fix your dependencies的问题
    activity和fragment的生命周期
  • 原文地址:https://www.cnblogs.com/kiko2014551511/p/15246877.html
Copyright © 2011-2022 走看看