基于Netty的群聊系统


1. 导入Netty的Maven依赖

 <!--netty依赖-->
<dependency>
  <groupId>io.netty</groupId>
  <artifactId>netty-all</artifactId>
  <version>4.1.65.Final</version>
</dependency>


2. 建立Netty聊天服务端

package com.wsp.train.netty.group;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * @Description netty聊天服务端
 * @Author wsp
 * @Date 2021/11/10 16:13
 **/
public class NettyChatServer {
    public static void main(String[] args) {
        NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            bootstrap.group(boosGroup, workerGroup)
                    .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 {
                            //心跳包检测 读、写、读写空闲状态
                            ch.pipeline().addLast(new IdleStateHandler(60, 120, 180, TimeUnit.SECONDS));
                            ch.pipeline().addLast(new NettyChatServerHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.bind(8888).sync();
            System.out.println("服务器启动完成");
            // 对关闭通道进行监听
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            boosGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}


3. 实现服务端处理类

package com.wsp.train.netty.group;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.EventExecutorGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description 服务端处理类
 * @Author wsp
 * @Date 2021/11/10 16:21
 **/
public class NettyChatServerHandler extends ChannelInboundHandlerAdapter {

    //聊天通道组
    private static ChannelGroup chatChannelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    //时间格式化器
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //连接成功
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketAddress socketAddress = ctx.channel().remoteAddress();
        System.out.println(sdf.format(new Date())+" "+socketAddress+" 上线了!");
    }

    //连接断开
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(sdf.format(new Date())+ctx.channel().remoteAddress()+" 下线了!");
    }

    //通道空闲状态,包括读空闲(READER_IDLE)、写空闲(WRITE_IDLE)、读写空闲(ALL_IDLE)
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event =  (IdleStateEvent) evt;
            String eventType = "";
            switch (event.state()) {
                case READER_IDLE:
                    eventType = "读空闲";
                    break;
                case WRITER_IDLE:
                    eventType = "写空闲";
                    break;
                case ALL_IDLE:
                    eventType = "读写空闲";
                    break;
                default:
                    break;
            }
            System.out.println(sdf.format(new Date())+ctx.channel().remoteAddress()+" 超时事件为----"+eventType);
        }
    }


    //将当前的连接通道channel加入到聊天通道组chatChannelGroup中,并向其它通道发送消息
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel chatChannel = ctx.channel();
        //将该客户加入到聊天室的信息发送給其它客户
        String msg  = sdf.format(new Date())+"【客户端】--" + chatChannel.remoteAddress() + " 已加入聊天组\n";
        chatChannelGroup.writeAndFlush(Unpooled.copiedBuffer(msg.getBytes()));
        //该连接加入channelGroup
        chatChannelGroup.add(chatChannel);
    }

    //将当前的连接通道channel从聊天通道组chatChannelGroup中移除,并向其它通道发送消息
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        String msg  = sdf.format(new Date())+"【客户端】" + channel.remoteAddress() + " 离开聊天了\n";
        chatChannelGroup.writeAndFlush(msg.getBytes());
        System.out.println("当前channelGroup大小为 "+chatChannelGroup.size());
    }

    //接收客户端的消息
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //获取当前的客户端channel
        Channel channel = ctx.channel();
        ByteBuf byteBuf = (ByteBuf) msg;
        String msgStr = byteBuf.toString(CharsetUtil.UTF_8);
        //遍历channelGroup,根据不同的情况,回送不同客户端不同的消息
        chatChannelGroup.forEach(ch -> {
            if (ch != channel) {
                byte[] response = (sdf.format(new Date()) + "【客户】" + channel.remoteAddress() + " 发送消息: " + msgStr).getBytes(StandardCharsets.UTF_8);
                ch.writeAndFlush(Unpooled.copiedBuffer(response));
            } else {
                byte[] response = (sdf.format(new Date()) + "【自己】发送了消息 " + msgStr).getBytes(StandardCharsets.UTF_8);
                ch.writeAndFlush(Unpooled.copiedBuffer(response));
            }
        });
    }

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


4. 建立Netty聊天客户端

package com.wsp.train.netty.group;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @Description netty聊天客户端
 * @Author wsp
 * @Date 2021/11/10 17:08
 **/
public class NettyChatClient {
    public static void main(String[] args) {
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            channel.pipeline().addLast(new NettyChatClientHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8888).sync();
            Channel channel = channelFuture.channel();
            SocketAddress socketAddress = channel.localAddress();
            System.out.println("连接成功 "+socketAddress+"============");
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String content = scanner.nextLine();
                ByteBuf byteBuf = Unpooled.copiedBuffer(content.getBytes(StandardCharsets.UTF_8));
                channel.writeAndFlush(byteBuf);
            }
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }
}


5. 实现客户端处理类

package com.wsp.train.netty.group;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.EventExecutorGroup;

/**
 * @Description netty聊天客户端处理器
 * @Author wsp
 * @Date 2021/11/10 17:11
 **/
public class NettyChatClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf)msg;
        System.out.println("服务端回复的消息为: "+byteBuf.toString(CharsetUtil.UTF_8));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值