基于Netty实现的尬聊Demo

分类专栏:
Netty相关

文章标签:
Netty
原创

基于Netty实现的尬聊聊天室

尬聊聊天室第二版,第一版在这---->>>>点我鸭

Netty编码解码器

编解码器

解码器:负责处理"入站InboundHandler"数据
编码器:负责"出站OutboundHandler"数据
StringEncoder/StringDecoder 对字符串处理
ObjectEncoder/ObjectDecoder 对java对象处理

Netty的编解码器实现了ChannelHandlerAdapter,也是一种特殊的ChannelHandler,依赖于ChannelPipeline,可以将多个编解码器链接在一起,实现复杂的转换逻辑

代码如下

public class MyChatServer {

    public static void main(String[] args) {

        // 可以自定义线程的数量
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        // 默认创建的线程数量  = CPU处理器数量 * 2
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler())
                // 当连接被阻塞时  BACKLOG代表的是 阻塞队列的长度
                .option(ChannelOption.SO_BACKLOG, 128)
                // 设置连接为保持活动的状态
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new MyChatServerInitializer());
        try {
            ChannelFuture future = serverBootstrap.bind(8899).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
public class MyChatServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        // 拿到通道里的管道
        ChannelPipeline pipeline = ch.pipeline();
        // 基于分隔符的一种解码器
        pipeline.addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter()));
        // 先解码 后编码
        pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
        pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
        // 增加自定义的处理器
        pipeline.addLast(new MyChatServerHandler());
    }
}
/**
 * 处理器的另一种实现方式
 * SimpleChannelInboundHandler是ChannelInboundHandlerAdapter的子类
 * 在父类的基础上封装了channelRead0方法,本质上也是处理读数据逻辑的方法
 */
public class MyChatServerHandler extends SimpleChannelInboundHandler {

    /**
     * 当多个通道传入handler使用通道组的管理方式
     * GlobalEventExecutor是一个全局事件执行器,单例
     */
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 刚刚建立连接时第一个被执行的方法
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush("[服务器] - " + ctx.channel().remoteAddress() + "连接成功\r\n");
        channelGroup.add(ctx.channel());
//        super.handlerAdded(ctx);
    }

    /**
     * 当连接被移除或者被断开最后会执行的方法
     * 此处会自动将channel从channel组中移除
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush("[服务器] - " + ctx.channel().remoteAddress() + "断开连接");
//        super.handlerRemoved(ctx);
    }

    /**
     * 读数据
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 广播给其他客户端
        Channel selfChannel = ctx.channel();
        Iterator<Channel> iterator = channelGroup.iterator();
        while (iterator.hasNext()) {
            Channel channel = iterator.next();
            // 广播给其他人
            if (selfChannel != channel) {
                channel.writeAndFlush("[服务器] - " + selfChannel.remoteAddress()
                        + "发送消息:" + msg + "\n");
                continue;
            }
            // 如果是本通道  返回一个回答
            String answer;
            if (((String) msg).length() == 0) {
                answer = "Please say something \r\n";
            } else {
                answer = "Did you say " + msg + " ?\r\n";
            }
            channel.writeAndFlush(answer);
        }
    }

    /**
     * 连接成功此时通道是活跃的
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.write("Welcome to server\r\n");
        ctx.write("It is " + new Date() + " now.\r\n");
        ctx.flush();
//        super.channelActive(ctx);
    }

    /**
     * 通道不活跃的方法处理用户下线等业务逻辑
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + "下线了");
//        super.channelInactive(ctx);
    }

    /**
     * 通用异常处理方法
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 关闭上下文 即通道
        ctx.close();
//        super.exceptionCaught(ctx, cause);
    }
}
public class MyChatClient {

    public static void main(String[] args) {

        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new MyChatClientInitializer());
        try {
            ChannelFuture future = bootstrap.connect("127.0.0.1", 8899).sync();
//            future.channel().closeFuture().sync();
            //通过键盘获取到要发送的数据
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            for (; ; ) {
                String msg = br.readLine();
                future.channel().writeAndFlush(msg + "\r\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }
}
public class MyChatClientInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter()));
        pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
        pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
        pipeline.addLast(new MyChatClientHandler());
    }
}
public class MyChatClientHandler extends SimpleChannelInboundHandler<String> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println(msg);
    }
}

实现

1)运行服务端

运行服务端

2)运行客户端44

44

3)运行客户端30

30

4)客户端下线

下线

图片来自本人CSDN

  • 作者:潘震
  • 评论

    留言