Netty聊天室

今天在学习Netty的时候顺便实现了一个网络聊天室!因为学过一点Swing,顺便就用Swing做了个聊天界面。

效果如下图:

java多人聊天室含语音聊天 java聊天室实现带界面_netty

为了节约时间,界面很丑,有兴趣的小伙伴可以自己再美化下界面!闲话不多说,直接上代码:

服务端

服务端包含ServerFrame.java和ServerHandler.java两个类

ServerFrame

package top.jacktgq.view.groupchat;

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
/**
 * 
 * @Title: ServerFrame.java 
 * @Package top.jacktgq.view.groupchat 
 * @Description: 服务器端
 * @author CandyWall   
 * @date 2021年1月30日 下午4:47:03 
 * @version V1.0
 */
public class ServerFrame extends JFrame {
    private JTextArea ta;

    public ServerFrame() {
        setLayout(new BorderLayout());
        ta = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(ta);
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        initFrame();
        // 初始化服务器端
        new Thread(() -> {
            initServer();
        }).start();
    }
    
    private void initFrame() {
        setTitle("Netty服务端");
        setVisible(true);
        setSize(500, 350);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ServerFrame();
            }
        });
    }
    
    private void initServer() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        
        try {
            ChannelFuture future = bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(new ServerHandler(ta));
                    }
                })
                .bind(8888);
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if(future.isSuccess()) {
                        ta.append("服务器启动成功!\n");
                    } else {
                        ta.append("服务器启动失败!\n");
                    }
                }
            }).sync();
            System.out.println("...");
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

ServerHandler

package top.jacktgq.view.groupchat;

import javax.swing.JTextArea;

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 top.jacktgq.utils.LogUtils;

public class ServerHandler extends SimpleChannelInboundHandler<String> {
    private JTextArea ta;
    
    public ServerHandler(JTextArea ta) {
        this.ta = ta;
    }

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

    //表示连接一旦建立,第一个被执行
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        String forwardMsg = LogUtils.getCurrentTime() + " [客户端 "+ channel.remoteAddress().toString().substring(1) +"] 加入群聊\n";
        ta.append(forwardMsg);
        //将该客户单加入聊天的信息推送给其他在线的客户端
        //该方法会将channelGroup中所有的channel遍历,并发送消息
        //这里是先群发了再加入组,所以不会发给自己
        channelGroup.writeAndFlush(forwardMsg);
        //将当前channel加入到channelGroup中
        channelGroup.add(channel);
    }
    
    //表示断开连接,将xx客户离开的信息推送给当前在线的客户
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        String forwardMsg = "[客户端 "+ channel.remoteAddress().toString().substring(1) +"] 离开群聊\n";
        ta.append(forwardMsg);
        channelGroup.writeAndFlush(forwardMsg);
        //这里不需要自己去把当前的channel从channelGroup中移除,netty内部已经实现
        System.out.println("channelGroup.size() = " + channelGroup.size());
    }
    
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        //获取到当前Channel
        Channel channel = ctx.channel();
        String forwardMsg = LogUtils.getCurrentTime() + " [客户端 " + channel.remoteAddress().toString().substring(1) + "] 说:" + msg + "\n";
        ta.append(forwardMsg);
        //这时我们遍历channelGroup,根据不同的情况,回送不同的消息
        channelGroup.forEach(ch -> {
            if (ch != channel) {    //不是当前的channel,转发消息
                ch.writeAndFlush(forwardMsg);
            } else {    //回显自己发送消息给自己
                ch.writeAndFlush(LogUtils.getCurrentTime() + " [我] 说:" + msg + "\n");
            }
        });
    }
}

客户端

客户端包含ClientFrame.java和ClientHandler.java两个类

ClientFrame

package top.jacktgq.view.groupchat;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
/**
 * 
 * @Title: ClientFrame.java 
 * @Package top.jacktgq.view.groupchat 
 * @Description: 客户端
 * @author CandyWall   
 * @date 2021年1月30日 下午4:46:43 
 * @version V1.0
 */
public class ClientFrame extends JFrame {
    public JTextArea ta;
    private Channel channel;

    public ClientFrame() {
        setLayout(new BorderLayout());
        JTextField tf = new JTextField();
        tf.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String msg = tf.getText();
                sendMsg(msg);
                tf.setText("");
            }
        });
        ta = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(ta);
        getContentPane().add(tf, BorderLayout.SOUTH);
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        initFrame();
        new Thread(() -> {
            connect();
        }).start();
    }
    
    private void sendMsg(String msg) {
        channel.writeAndFlush(msg);
    }
    
    private void initFrame() {
        setTitle("Netty客户端");
        setVisible(true);
        setSize(500, 350);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ClientFrame();
            }
        });
    }
    
    private void connect() {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        
        try {
            ChannelFuture future = bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(new ClientHandler(ta));
                    }
                })
                .connect("localhost", 8888);
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if(future.isSuccess()) {
                        ta.append("登录成功!\n");
                        channel = future.channel();
                    } else {
                        ta.append("登录失败!\n");
                    }
                }
            }).sync();
            channel.closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }
}

ClientHandler

package top.jacktgq.view.groupchat;

import javax.swing.JTextArea;

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

public class ClientHandler extends SimpleChannelInboundHandler<String> {
    private JTextArea ta;
    public ClientHandler(JTextArea ta) {
        this.ta = ta;
    }
    
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        // 显示消息
        ta.append(msg);
    }
}

LogUtils工具类

客户端和服务端的代码中关于日期显示的地方用到了这个工具类,可以获取到格式化的日期,具体格式为 yyyy年MM月dd日 HH:mm:ss:SSS

package top.jacktgq.utils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 
 * @Title: TimeUtils.java 
 * @Package top.jacktgq 
 * @Description: 自定义日志打印类
 * @author CandyWall   
 * @date 2020年11月1日 下午7:35:23 
 * @version V1.0
 */
public class LogUtils {
	
	/**
	 * 获取当前系统时间,并进行格式化
	 */
	public static String getCurrentTime() {
		LocalDateTime now = LocalDateTime.now();
		return now.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss:SSS"));
	}
	
	/**
	 * @param info :要输出的内容
	 */
	public static void log(String info) {
		log("", info);
	}
	
	/**
	 * 
	 * @param className	:类名
	 * @param info		:要输出的内容
	 */
	public static void log(String className, String info) {
		System.out.println(getCurrentTime() + " <" + className + "> [" + Thread.currentThread().getName() + "] : " + info);
	}
}

写在最后:这个小案例希望能帮到Netty的初学者,帮助你们提起学习的兴趣,有什么不对的地方,还请大家在评论区指正!