Netty9-Netty实现群聊系统 并附 实现点对点私聊思路

10 篇文章 0 订阅
  1. 编写一个 Netty 群聊系统,实现服务器端和客户端之间的数据简单通讯(非阻塞)
  2. 实现多人群聊
  3. 服务器端:可以监测用户上线,离线,并实现消息转发功能
  4. 客户端:通过channel 可以无阻塞发送消息给其它所有用户,同时可以接受其它用
    户发送的消息(有服务器转发得到)

Server

package com.atguigu.netty.NettyGroupChat;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.security.acl.Group;

/**
 * @Description: ···
 * @author: Freedom
 * @QQ: 1556507698
 * @date:2022/6/24 16:41
 */

public class nettyGroupChatServer {

    private int port; //监听端口


    private nettyGroupChatServer(int port) {
        //接受一个端口
        this.port = port;
    }

    /**
     * run 方法处理客户端请求
     */
    public void run() throws InterruptedException {
        //创建两个线程组
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        try {

            //客户端程序启动引导类
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    //设置线程队列得到连接个数
                    .option(ChannelOption.SO_BACKLOG, 128)
                    //设置保持活动连接状态
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //获取到Pipeline
                            ChannelPipeline pipeline = ch.pipeline();
                            //向Pipeline里加入一个解码器
                            pipeline.addLast("decoder", new StringDecoder());
                            //向Pipeline加入编码器
                            pipeline.addLast("encoder", new StringEncoder());
                            //加入自己的业务处理Handle
                            pipeline.addLast(new nettyGroupChatServerHandle());
                        }
                    });
            System.out.println("Netty 服务器启动");
            ChannelFuture channelFuture = b.bind(port).sync();

            //监听关闭事件
            channelFuture.channel().closeFuture().sync();

        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new nettyGroupChatServer(7000).run();
    }

}

ServerHandle

package com.atguigu.netty.NettyGroupChat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: ···
 * @author: Freedom
 * @QQ: 1556507698
 * @date:2022/6/24 17:04
 */

public class nettyGroupChatServerHandle extends SimpleChannelInboundHandler<String> {

    //定义一个Channel组管理所有的Channel
    //GlobalEventExecutor 是一个全局的事件执行器是一个单例
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);


    //TODO 如果要实现点对点私聊 方案1
    //可以使用一个hashmap管理
    public static Map<String,Channel>  channels = new HashMap<>();

    //TODO 实现点对点方案2
    public static Map<User,Channel>  channelUser = new HashMap<>();

    //时间
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 第一个被调用的,表示链接建立,一旦建立 第一个个被执行
     * 将当前的Channel 加入到 channelGroup Channel组
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //获取Channel
        Channel channel = ctx.channel();
        //将该客户端加入聊天的信息 推送给其他在线的客户

        //channelGroup.writeAndFlush  把当前管理的所有Channel 遍历 并发送消息
        channelGroup.writeAndFlush("[客户端]" + channel.remoteAddress() + "加入聊天");
        //放入管理组
        channelGroup.add(channel);

        //TODO 实现私聊 放进去后可以在map中拿到Channel
        channels.put("id-100", channel);

        System.out.println("handlerAdded Channel Group 大小" + channelGroup.size());
    }

    /**
     * 断开连接被触发
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {

        channelGroup.writeAndFlush("[客户端]" + ctx.channel().remoteAddress() + "离开聊天");
        //每执行一次handlerRemoved大小就会减少
        System.out.println("Removed Channel Group 大小" + channelGroup.size());
    }

    /**
     * Channel处于活动状态 提示上线
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + "上线了 -.-");
    }

    /**
     * Channel处于非活动状态 提示离线
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + "离线了 -.-");

    }

    /**
     * 读取数据
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        //获取到当前Channel
        Channel channel = ctx.channel();

        //遍历ChannelGroup 根据不同的情况 会送不同的消息

        channelGroup.forEach(ch -> {

            //当不是自己的Channel 即 不是当前Channel
            if (ch != channel){
                //直接转发
                ch.writeAndFlush("[客户] " + channel.remoteAddress() + "发送消息" + msg + "\n");
            }else {
                //是自己的Channel
                ch.writeAndFlush("[自己] " + "发送消息" + msg + "\n" );

            }

        });
    }

    /**
     * 发生异常时触发此方法
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}

Client

package com.atguigu.netty.NettyGroupChat;

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.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 io.netty.util.CharsetUtil;

import java.util.Scanner;

/**
 * @Description: ···
 * @author: Freedom
 * @QQ: 1556507698
 * @date:2022/6/25 16:29
 */

public class nettyGroupChatClient {
    //定义相关属性
    private final String HOST;
    private final int PORT;

    public nettyGroupChatClient(String HOST, int PORT) {
        this.HOST = HOST;
        this.PORT = PORT;
    }


    public void run() throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            //设置
            Bootstrap bootstrap = new Bootstrap();
            bootstrap
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //得到pipeline
                            ChannelPipeline pipeline = ch.pipeline();
                            //加入相关handler
                            //向Pipeline里加入一个解码器
                            pipeline.addLast("decoder", new StringDecoder());
                            //向Pipeline加入编码器
                            pipeline.addLast("encoder", new StringEncoder());
                            //加入自定义处理器
                            pipeline.addLast(new nettyGroupChatHandle());
                        }
                    });

            ChannelFuture sync = bootstrap.connect(HOST, PORT).sync();
            //提示信息 得到Channel
            Channel channel = sync.channel();
            System.out.println("---------------" + channel.localAddress() + "-----");
            //客户端需要输入信息
            //创建扫描器
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String s = scanner.nextLine();
                //听过Channel 发送到服务器端
                channel.writeAndFlush(s);
            }
        } finally {
            //关闭
            group.shutdownGracefully();
        }


    }

    public static void main(String[] args) throws InterruptedException {
        new nettyGroupChatClient("127.0.0.1", 7000).run();
    }
}

ClientHandle

package com.atguigu.netty.NettyGroupChat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @Description: ···
 * @author: Freedom
 * @QQ: 1556507698
 * @date:2022/6/25 16:43
 */

public class nettyGroupChatHandle extends SimpleChannelInboundHandler<String> {

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值