基于Netty的多人聊天室实现:从服务器搭建到客户端交互
基于Netty的多人聊天室实现:从服务器搭建到客户端交互
本篇博客将带领大家使用Netty构建一个功能完善的多人聊天室。我们将深入探讨服务器端和客户端的实现细节,包括用户登录、聊天室列表、消息发送和私聊等功能。
一、服务器端搭建
首先,我们使用Netty框架搭建服务器端,负责监听客户端连接、处理消息转发等核心功能。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(); }}
二、消息处理逻辑
MultiChatServerHandler类负责处理服务器端的消息处理逻辑,包括用户登录、聊天室列表、消息发送和私聊功能。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
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(' '); } 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('
'); 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('
'); 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(); }}
三、客户端实现
客户端代码负责连接服务器、发送消息和接收消息等功能。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(); }}
四、客户端消息处理
MultiChatClientHandler类实现了客户端的消息处理逻辑,包括接收服务器端的消息和向服务器端发送消息。javaimport io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;
public class MultiChatClientHandler extends SimpleChannelInboundHandler
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); }}
五、运行测试
- 将上述代码分别保存为
MultiChatServer.java、MultiChatServerHandler.java、MultiChatClient.java和MultiChatClientHandler.java文件。2. 使用命令行编译代码:javac *.java3. 运行服务器端:java MultiChatServer4. 运行客户端:java MultiChatClient
六、交互示例
客户端输入
localhost 8080LOGIN|test|123456LISTMSG|room1|Hello everyone!PRIVATE|user1|Hello user1!
服务器端输出
Client connected: /127.0.0.1:54885Login successful: testAvailable chat rooms:room1room2[test] Hello everyone![test] (private) Hello user1!
通过以上步骤,我们成功搭建了一个基于Netty的多人聊天室。该聊天室支持用户登录、获取聊天室列表、发送消息到指定聊天室以及私聊等功能。
原文地址: http://www.cveoy.top/t/topic/f10r 著作权归作者所有。请勿转载和采集!