netty示例-tcp协议传输

  1. 1.TcpServer.java
  2. 2.TestMyServerHandler.java
  3. 3.TcpClient.java
  4. 4.TestMyClientHandler.java
  5. 5.TcpHandler拦截器解答

1.TcpServer.java

public class TcpServer {
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup wordGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, wordGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel sc) throws Exception {
                    ChannelPipeline pipeline = sc.pipeline();
                    pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4,0,4));
                    pipeline.addLast(new LengthFieldPrepender(4));
                    pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
                    pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
                    pipeline.addLast(new TestMyServerHandler());

                }
            });
            ChannelFuture channelFuture = serverBootstrap.bind(8081).sync();
            System.out.println("服务器...");
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            bossGroup.shutdownGracefully();
            wordGroup.shutdownGracefully();
        }
    }
}

2.TestMyServerHandler.java

public class TestMyServerHandler extends SimpleChannelInboundHandler<String>{

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
        System.out.println(channelHandlerContext.channel().remoteAddress()+","+msg);
        channelHandlerContext.writeAndFlush("from server"+UUID.randomUUID());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.channel().close();
    }
}

3.TcpClient.java

public class MyClient {
    public static void main(String[] args) {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel sc) throws Exception {
                    ChannelPipeline pipeline = sc.pipeline();
                    pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4));
                    pipeline.addLast(new LengthFieldPrepender(4));
                    pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
                    pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
                    pipeline.addLast(new TestMyClientHandler());
                }

            });
            ChannelFuture channelFuture = bootstrap.connect("localhost", 8081).sync();
            System.out.println("客户端...");
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally{
            eventLoopGroup.shutdownGracefully();
        }
    }
}

4.TestMyClientHandler.java

public class TestMyClientHandler extends SimpleChannelInboundHandler<String>{

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
        System.out.println(channelHandlerContext.channel().remoteAddress());
        System.out.println("client output"+msg);
        channelHandlerContext.writeAndFlush("from client"+LocalDateTime.now());
    }
channelActive()方法在socket通道建立时被触发
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush("来自客户端得问候");
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

5.TcpHandler拦截器解答

LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4,0,4));

LengthFieldPrepender(4));

上述两种拦截器,编解码长度拦截,对应的参数与LengthFieldBasedFrameDecoder类的参数maxFrameLength一致。

Integer.MAX_VALUE 字节是int,所以对应的长度均为4. (如上三个4)

StringDecoder和StringEncoder是对传输的string类型数据进行编解码处理的拦截器

文章标题:netty示例-tcp协议传输

发布时间:2020-01-17, 09:52:46

最后更新:2020-01-17, 09:52:47