netty 收发数据开发

服务端:

import io.netty.bootstrap.ServerBootstrap;
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.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;


public class SubReqServer {

    public void bind(int nPort) throws Exception {

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try{
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 100)
            .handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<SocketChannel>(){
                @Override
                public void initChannel(SocketChannel ch) throws Exception{
                    ch.pipeline()
                    .addLast(
                            new ObjectDecoder(1024*1024,
                                    ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())))
                    .addLast(new ObjectEncoder())
                    .addLast(new SubReqServerHandler());
                }
            });

            ChannelFuture f = b.bind(nPort).sync();
            System.out.println("---------------wait for connect");
            f.channel().closeFuture().sync();
        }finally {
            System.out.println("---------------wait for connect  Error!");
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }


    public static void main(String[] args){
        int nPort = 7788;
        nPort = Integer.valueOf(nPort);
        System.out.println("---------------Main start");
        try {
            new SubReqServer().bind(nPort);
        } catch (Exception e) {
            System.out.println("---------------Main Error");
            e.printStackTrace();
        }
    }
}

服务端Handler:

import com.cetcnav.suo.ADSB.util.ByteConvertUtil;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class SubReqServerHandler extends ChannelInboundHandlerAdapter{

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)throws Exception {
        byte[] bytes =(byte[]) msg;
        System.out.println(ByteConvertUtil.bytes2HexString(bytes));
    }

}

客户端:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
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.LengthFieldPrepender;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.serialization.ObjectEncoder;


public class NettyClient implements Runnable{
    static Logger log = LoggerFactory.getLogger(NettyClient.class);


    @Override
    public void run() {
        new NettyClient().connect(7788,"127.0.1.1");
    }

    private static Channel channel ;

    public static void connect(int port,String host){
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class)
        .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("decoder", new ObjectEncoder());
//                pipeline.addLast("frameEncoder", new LengthFieldPrepender(8));
                pipeline.addLast(new NettyClientHandler());
            }
        });
        try {
           //发起异步连接操作
           ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
           channel = channelFuture.channel();
           System.out.println(channel);
           channel.closeFuture().sync();
        } catch (InterruptedException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }finally{
            //关闭,释放线程资源
            group.shutdownGracefully();
        }
    }


  public void sendMessage(Object msg){//连接成功后,通过Channel提供的接口进行IO操作
      System.out.println(222);
      try {
          if (channel != null && channel.isOpen()) {
              System.out.println(1111);
              channel.writeAndFlush(msg).sync();     //(1)
           } else {
              throw new Exception("channel is null | closed");
           }
      } catch (Exception e) {
    //      sendReconnectMessage();
            e.printStackTrace();
      }  
  } 

  private static ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor)Executors.newScheduledThreadPool(15);

    public static void main(String[] args) throws InterruptedException {
        byte[] bytes=new ByteUtils().test();
        executor.execute(new NettyClient());
        System.out.println(333);
        Thread.sleep(3000);
        new NettyClient().sendMessage(bytes);

    }
}

客户端Handler:

import java.io.UnsupportedEncodingException;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * Handles a server-side channel.
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter{ // (1)

//  @Override
//  public void channelActive(ChannelHandlerContext ctx){
//      System.out.println("----------------handler channelActive-----准备发送十个数据-------");
//      
//      for(int i = 0; i<10; i++){
//          int req=1;
//          ctx.write(req);
//      }
//      ctx.flush();
//  }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
        ByteBuf buf = (ByteBuf) msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);// (3)
        try {
            String body = new String(req, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值