基于Netty的多人聊天室实现

本文介绍了一个基于Netty框架的多人聊天室的实现,主要包括服务器端和客户端两部分。其中服务器端实现了用户登录、聊天室列表、消息发送和私聊功能,客户端实现了接收服务器端的消息和向服务器端发送消息的功能。

一、服务器端

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
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 io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;

import java.util.concurrent.ConcurrentHashMap;

public class MultiChatServer {
    private final int port;
    private final ConcurrentHashMap<String, ChannelHandlerContext> userMap = new ConcurrentHashMap<>();
    private final EventExecutorGroup group = new DefaultEventExecutorGroup(16);

    public MultiChatServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringDecoder(), new StringEncoder(), new MultiChatServerHandler(userMap, group));
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        new MultiChatServer(port).run();
    }
}

代码说明:

  • MultiChatServer 类负责启动服务器,监听客户端连接请求,并处理连接请求。
  • userMap 用于存储用户和其连接的 ChannelHandlerContext
  • group 用于处理异步操作。
  • 代码中使用了 NioEventLoopGroup 来处理网络事件,NioServerSocketChannel 来创建服务器通道。
  • ChannelInitializer 用于初始化每个连接的 ChannelPipeline,添加 StringDecoderStringEncoder 用于编解码字符串消息,并添加 MultiChatServerHandler 处理消息。

二、MultiChatServerHandler 类

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.EventExecutorGroup;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MultiChatServerHandler extends SimpleChannelInboundHandler<String> {
    private final ConcurrentHashMap<String, ChannelHandlerContext> userMap;
    private final EventExecutorGroup group;

    public MultiChatServerHandler(ConcurrentHashMap<String, ChannelHandlerContext> userMap, EventExecutorGroup group) {
        this.userMap = userMap;
        this.group = group;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Client connected: " + ctx.channel().remoteAddress());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Client disconnected: " + ctx.channel().remoteAddress());
        userMap.values().remove(ctx);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        String[] tokens = msg.split("|");
        String command = tokens[0];

        switch (command) {
            case "LOGIN":
                handleLogin(ctx, tokens[1], tokens[2]);
                break;
            case "LIST":
                handleList(ctx);
                break;
            case "MSG":
                handleMessage(ctx, tokens[1], tokens[2]);
                break;
            case "PRIVATE":
                handlePrivateMessage(ctx, tokens[1], tokens[2]);
                break;
            default:
                ctx.writeAndFlush("Invalid command: " + command);
                break;
        }
    }

    private void handleLogin(ChannelHandlerContext ctx, String username, String password) {
        if (userMap.containsKey(username)) {
            ctx.writeAndFlush("User already logged in: " + username);
        } else {
            userMap.put(username, ctx);
            ctx.writeAndFlush("Login successful: " + username);
        }
    }

    private void handleList(ChannelHandlerContext ctx) {
        StringBuilder sb = new StringBuilder();
        sb.append("Available chat rooms:
");
        for (Map.Entry<String, ChannelHandlerContext> entry : userMap.entrySet()) {
            sb.append(entry.getKey()).append("\n");
        }
        ctx.writeAndFlush(sb.toString());
    }

    private void handleMessage(ChannelHandlerContext ctx, String roomName, String message) {
        StringBuilder sb = new StringBuilder();
        sb.append("[").append(ctx.channel().remoteAddress()).append("] ").append(message).append("\n");
        for (Map.Entry<String, ChannelHandlerContext> entry : userMap.entrySet()) {
            if (entry.getKey().equals(roomName)) {
                entry.getValue().writeAndFlush(sb.toString());
            }
        }
    }

    private void handlePrivateMessage(ChannelHandlerContext ctx, String recipient, String message) {
        StringBuilder sb = new StringBuilder();
        sb.append("[").append(ctx.channel().remoteAddress()).append("] (private) ").append(message).append("\n");
        if (userMap.containsKey(recipient)) {
            userMap.get(recipient).writeAndFlush(sb.toString());
        } else {
            ctx.writeAndFlush("User not found: " + recipient);
        }
    }

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

代码说明:

  • MultiChatServerHandler 类处理来自客户端的消息,并根据消息类型进行不同的处理。
  • handleLogin 方法处理用户登录请求。
  • handleList 方法处理聊天室列表请求。
  • handleMessage 方法处理普通消息,将消息广播到指定的房间。
  • handlePrivateMessage 方法处理私聊消息,将消息发送给指定的接收者。

三、客户端

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
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 java.io.BufferedReader;
import java.io.InputStreamReader;

public class MultiChatClient {
    private final String host;
    private final int port;
    private ChannelHandlerContext ctx;

    public MultiChatClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringDecoder(), new StringEncoder(), new MultiChatClientHandler());
                        }
                    });

            ChannelFuture f = b.connect(host, port).sync();
            ctx = f.channel().pipeline().context(MultiChatClientHandler.class);
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String line = in.readLine();
                if (line == null) {
                    break;
                }
                ctx.writeAndFlush(line + "\n");
            }
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        String host = "localhost";
        int port = 8080;
        new MultiChatClient(host, port).run();
    }
}

代码说明:

  • MultiChatClient 类负责启动客户端,连接服务器,并向服务器发送消息。
  • 代码中使用了 NioEventLoopGroup 来处理网络事件,NioSocketChannel 来创建客户端通道。
  • ChannelInitializer 用于初始化每个连接的 ChannelPipeline,添加 StringDecoderStringEncoder 用于编解码字符串消息,并添加 MultiChatClientHandler 处理消息。
  • 客户端通过 BufferedReader 从控制台读取用户输入,并将消息发送给服务器。

四、MultiChatClientHandler 类

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

public class MultiChatClientHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println(msg);
    }

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

代码说明:

  • MultiChatClientHandler 类处理来自服务器的消息,并将其打印到控制台。

总结

该项目是一个基于Netty框架实现的多人聊天室,包含服务器端和客户端两部分。服务器端实现了用户登录、聊天室列表、消息发送和私聊功能,客户端实现了接收服务器端的消息和向服务器端发送消息的功能。代码使用简洁明了,易于理解和扩展。

基于Netty的多人聊天室实现

原文地址: https://www.cveoy.top/t/topic/f1fI 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录