Netty网络聊天室,使用Java Swing实现聊天窗口

Netty聊天室

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

效果如下图:

Java Swing实现的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的初学者,帮助你们提起学习的兴趣,有什么不对的地方,还请大家在评论区指正!

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
首先,需要了解什么是NettyNetty是一个异步事件驱动的网络应用框架,用于快速开发可维护的高性能协议服务器和客户端。 接下来,我们可以开始实现聊天室功能。一个简单的聊天室应该具备以下功能: 1. 用户连接和断开连接的处理; 2. 用户发送消息和接收消息的处理; 3. 消息广播给所有在线用户。 下面是一个简单的实现: 1. 用户连接和断开连接的处理 Netty提供了ChannelHandlerAdapter和ChannelInboundHandlerAdapter两个抽象类,我们可以继承其中一个来实现自己的Handler。这里我们使用ChannelInboundHandlerAdapter。 ```java public class ChatServerHandler extends ChannelInboundHandlerAdapter { // 用户列表,用于保存所有连接的用户 private static List<Channel> channels = new ArrayList<>(); // 新用户连接时,将连接加入用户列表 @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { channels.add(ctx.channel()); System.out.println(ctx.channel().remoteAddress() + " 上线了"); } // 用户断开连接时,将连接从用户列表中移除 @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { channels.remove(ctx.channel()); System.out.println(ctx.channel().remoteAddress() + " 下线了"); } } ``` 2. 用户发送消息和接收消息的处理 Netty的数据传输是通过ByteBuf来实现的,因此我们需要将ByteBuf转换为字符串进行处理。 ```java public class ChatServerHandler extends ChannelInboundHandlerAdapter { // 用户列表,用于保存所有连接的用户 private static List<Channel> channels = new ArrayList<>(); // 新用户连接时,将连接加入用户列表 @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { channels.add(ctx.channel()); System.out.println(ctx.channel().remoteAddress() + " 上线了"); } // 用户断开连接时,将连接从用户列表中移除 @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { channels.remove(ctx.channel()); System.out.println(ctx.channel().remoteAddress() + " 下线了"); } // 接收用户发送的消息并处理 @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; String received = buf.toString(CharsetUtil.UTF_8); System.out.println(ctx.channel().remoteAddress() + ": " + received); broadcast(ctx, received); } // 将消息广播给所有在线用户 private void broadcast(ChannelHandlerContext ctx, String msg) { for (Channel channel : channels) { if (channel != ctx.channel()) { channel.writeAndFlush(Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8)); } } } } ``` 3. 消息广播给所有在线用户 我们可以使用broadcast方法将接收到的消息广播给所有在线用户。 ```java public class ChatServerHandler extends ChannelInboundHandlerAdapter { // 用户列表,用于保存所有连接的用户 private static List<Channel> channels = new ArrayList<>(); // 新用户连接时,将连接加入用户列表 @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { channels.add(ctx.channel()); System.out.println(ctx.channel().remoteAddress() + " 上线了"); } // 用户断开连接时,将连接从用户列表中移除 @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { channels.remove(ctx.channel()); System.out.println(ctx.channel().remoteAddress() + " 下线了"); } // 接收用户发送的消息并处理 @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; String received = buf.toString(CharsetUtil.UTF_8); System.out.println(ctx.channel().remoteAddress() + ": " + received); broadcast(ctx, received); } // 将消息广播给所有在线用户 private void broadcast(ChannelHandlerContext ctx, String msg) { for (Channel channel : channels) { if (channel != ctx.channel()) { channel.writeAndFlush(Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8)); } } } } ``` 接下来我们需要编写一个启动类,用于启动聊天室服务器。 ```java public class ChatServer { public static void main(String[] args) throws Exception { // 创建EventLoopGroup EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { // 创建ServerBootstrap ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ChatServerHandler()); } }); // 启动服务器 ChannelFuture channelFuture = serverBootstrap.bind(8888).sync(); System.out.println("服务器启动成功"); // 关闭服务器 channelFuture.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } } ``` 现在,我们就完成了一个简单的聊天室服务器。可以通过运行ChatServer类启动服务器,然后使用telnet命令连接服务器进行聊天。 ```sh telnet localhost 8888 ``` 输入发送的消息,即可将消息广播给所有在线用户。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值