netty学习(二) -基于socket的服务端和客户端通讯

4 篇文章 0 订阅

实现客户端和服务端之间的通讯,
客户端给服务端发送消息,同时服务端给客户端发送一条反馈消息

服务端代码

public class SocketServer {

    private static final Logger logger = LoggerFactory.getLogger(SocketServer.class);

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup boosGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boosGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    logger.info("有客户端连接到服务器:{}", ch.remoteAddress());
                    ChannelPipeline pipeline = ch.pipeline();
                    // 
                    pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                    pipeline.addLast(new LengthFieldPrepender(4));
                    // 字符串解码器与编码器
                    pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
                    pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
                    pipeline.addLast(new SocketServerHandler());
                }
            });
            ChannelFuture channelFuture = bootstrap.bind(8899).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            boosGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

public class SocketServerHandler extends SimpleChannelInboundHandler<String> {
    private static final Logger logger = LoggerFactory.getLogger(SocketServerHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        logger.info("request:{}", msg);
        ctx.writeAndFlush(LocalTime.now() + " hello," + msg);
    }
}

客户端代码

public class SocketClient {
    private static final Logger logger = LoggerFactory.getLogger(SocketClient.class);

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workerGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    logger.info("成功连接到服务器:{}", ch.remoteAddress());

                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                    pipeline.addLast(new LengthFieldPrepender(4));
                    pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
                    pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
                    pipeline.addLast(new SocketClientHandler());
                }
            });
            ChannelFuture channelFuture = bootstrap.connect("localhost", 8899).sync();
            Scanner scanner = new Scanner(System.in);
            while(scanner.hasNext()){
                String next = scanner.next();
                logger.info("send:{}",next);
                channelFuture.channel().writeAndFlush(next);
            }
            channelFuture.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}

public class SocketClientHandler extends SimpleChannelInboundHandler<String> {
    private static final Logger logger = LoggerFactory.getLogger(SocketClientHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        logger.info("response:{}", msg);
    }
}

实现效果

客户端给服务器发送消息: 我是客户端
服务端给客户端反馈消息: 12:14:09.976 hello,我是客户端
在这里插入图片描述
在这里插入图片描述

总结

StringEncoder和StringDecoder

字符串类型的编码器和解码器,通讯的底层是使用字节流实现的,这2个类可以帮我们实现字符串和字节之间的相互转换。

LengthFieldBasedFrameDecoder

在网络传输过程中会出现分包 粘包等异常情况,导致我们读取数据不完整,这个解码器是netty为了解决这个问题而提供的一个通用方案。与它配套的还有一个编码器叫做LengthFieldPrepender
更多详细分析可以参考这位大佬的帖子,写的始分详细,图文并茂,值得一读

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值