基于Netty的多人聊天室:Java实现及完整代码示例

本教程将引导您使用Java和Netty框架创建一个多人聊天室应用。我们将涵盖服务器端和客户端的实现,并提供完整的代码示例。

一、项目概述

本项目将实现一个简单的多人聊天室,具备以下功能:

  • 用户登录: 用户可以使用用户名和密码登录聊天室。* 聊天室列表: 用户可以查看可加入的聊天室列表。* 消息发送: 用户可以在聊天室中发送消息。* 私聊: 用户可以向其他用户发送私聊消息。

二、服务器端实现

2.1 服务器端主程序javaimport 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();    }}

代码说明:

  1. 创建 ServerBootstrap 实例用于配置服务器。2. 设置 NioEventLoopGroup 用于处理IO操作。3. 指定使用 NioServerSocketChannel 作为服务器通道类型。4. 设置 childHandler 用于处理客户端连接,并添加 StringDecoderStringEncoderMultiChatServerHandler 到管道中。5. 绑定端口并启动服务器。

2.2 服务器端消息处理器javaimport 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 { 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 users:

'); for (Map.Entry<String, ChannelHandlerContext> entry : userMap.entrySet()) { sb.append(entry.getKey()).append(' '); } ctx.writeAndFlush(sb.toString()); }

private void handleMessage(ChannelHandlerContext ctx, String recipient, String message) {        StringBuilder sb = new StringBuilder();        sb.append('[').append(ctx.channel().remoteAddress()).append('] ').append(message).append('

'); if (userMap.containsKey(recipient)) { userMap.get(recipient).writeAndFlush(sb.toString()); } else { ctx.writeAndFlush('User not found: ' + recipient); } }

private void handlePrivateMessage(ChannelHandlerContext ctx, String recipient, String message) {        handleMessage(ctx, recipient, message);     }

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

代码说明:

  1. MultiChatServerHandler 继承自 SimpleChannelInboundHandler<String>,用于处理字符串类型的消息。2. channelActivechannelInactive 方法分别处理客户端连接和断开连接事件。3. channelRead0 方法处理接收到的消息,根据消息类型调用不同的处理方法。4. handleLogin 方法处理用户登录请求。5. handleList 方法返回当前在线用户列表。6. handleMessage 方法处理消息发送请求。7. handlePrivateMessage 方法处理私聊消息发送请求。

三、客户端实现

3.1 客户端主程序javaimport 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 + '

'); } } finally { group.shutdownGracefully(); } }

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

代码说明:

  1. 创建 Bootstrap 实例用于配置客户端。2. 设置 NioEventLoopGroup 用于处理IO操作。3. 指定使用 NioSocketChannel 作为客户端通道类型。4. 设置 handler 用于处理服务端响应,并添加 StringDecoderStringEncoderMultiChatClientHandler 到管道中。5. 连接服务器并启动客户端。

3.2 客户端消息处理器javaimport io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;

public class MultiChatClientHandler extends SimpleChannelInboundHandler { @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();    }}

代码说明:

  1. MultiChatClientHandler 继承自 SimpleChannelInboundHandler<String>,用于处理字符串类型的消息。2. channelRead0 方法处理接收到的服务端消息,并打印到控制台。

四、编译和运行

  1. 将 Netty 的 jar 包添加到您的项目中。2. 编译服务器端和客户端代码。3. 首先启动服务器端程序。4. 然后启动多个客户端程序,并连接到服务器。5. 客户端可以输入以下命令进行操作: * LOGIN|username|password:登录聊天室,例如 LOGIN|user1|123456。 * LIST:查看当前在线用户列表。 * MSG|recipient|message:发送消息给指定用户,例如 MSG|user2|Hello, user2!。 * PRIVATE|recipient|message:发送私聊消息给指定用户,效果和 MSG 命令相同,例如 PRIVATE|user2|This is a private message.

总结

本文介绍了如何使用 Netty 构建一个简单的多人聊天室应用。您可以根据自己的需求扩展此应用程序,例如添加群聊功能、文件传输功能等.

基于Netty的多人聊天室:Java实现及完整代码示例

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

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