一、demo要求
1)编写一个Netty个人对个人聊天系统,实现服务器端和客户端之间的数据简单通讯(非阻塞)
2)实现单人对单人聊
3)服务器端:可以监测用户上线,离线,并实现消息转发功能。
4)客户端:通过channel可以无阻塞发送消息给对应用户(有服务器转发得到)
5)目的:进一步理解Netty非阻塞网络编程机制。
二、服务器代码
package com.tfq.netty.netty.personalchat;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
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;
/**
* @author: fqtang
* @date: 2024/04/03/13:39
* @description: 描述
*/
public class PersonChatServer {
//监听端口
private int port;
public PersonChatServer(int port) {
this.port = port;
}
/**
* 处理客户端的请求
*/
public void run() throws InterruptedException {
//创建两个线程组
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup(8);
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//获取到pipeline
ChannelPipeline pipeline = ch.pipeline();
//向pipeline加入一个解码器
pipeline.addLast("decoder", new StringDecoder());
//向pipeline加入一个编码器
pipeline.addLast("encoder", new StringEncoder());
//加入自己的业务处理handler
pipeline.addLast(new PToPChatServerHandler());
}
});
System.out.println("netty 服务器启动");
ChannelFuture channelFuture = serverBootstrap.bind(port)
.sync();
channelFuture.channel()
.closeFuture()
.sync();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
try {
new PersonChatServer(7888).run();
} catch(InterruptedException e) {
throw new RuntimeException(e);
}
}
}
服务器端的Handler
package com.tfq.netty.netty.personalchat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
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;
/**
* @author: fqtang
* @date: 2024/04/03/13:53
* @description: 个人对个人聊天
*/
public class PToPChatServerHandler extends SimpleChannelInboundHandler<String> {
//使用一个hashmap管理账户
private static HashMap<User, Channel> userChannels = new HashMap<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* 表示连接建立,一旦连接,第一个被执行
* 将当前channel加入到 channelGroup
*
* @param ctx
* @throws Exception
*/
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
//将该客户加入聊天的信息推送给其他在线的客户端
userChannels.put(new User(channel.hashCode() + "", "client" + new Random().nextInt(100)), channel);
userChannels.forEach((user, uChannel) -> {
channel.writeAndFlush(sdf.format(new Date()) + ",现在有的[客户]:" + uChannel.remoteAddress() + "加入聊天.请选择一个客户Id进行私聊......."+uChannel.hashCode()+"\n");
});
}
/**
* 表示channel 处于活动上线,提示 xx上线
*
* @param ctx
* @throws Exception
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel()
.remoteAddress() + " 在[ " + sdf.format(new Date()) + " ] 上线了~");
}
/**
* 表示channel 处于离线,提示 xx离线
*
* @param ctx
* @throws Exception
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel()
.remoteAddress() + "在 " + sdf.format(new Date()) + " 离线了~");
}
/**
* 断开连接,将XX客户离开信息推送给当前在线的客户
*
* @param ctx
* @throws Exception
*/
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
userChannels.keySet().removeIf(key ->key.getId().equals(String.valueOf(channel.hashCode())));
System.out.println("移除通道,当前账户总数量:" + userChannels.size());
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
//获取当前通道channel
Channel channel = ctx.channel();
userChannels.forEach((user, uChannel) -> {
channel.writeAndFlush(sdf.format(new Date()) + ",现在有的[客户]:" + uChannel.remoteAddress() + ".请选择一个客户Id进行私聊....." + user.getId() + "..\n");
});
String[] start = msg.split("id_");
String[] end = start[1].split(":");
String targetId = end[0];
//私对私发信息聊天
userChannels.forEach((user, uChannel) -> {
if(targetId.equals(user.getId()) && uChannel != channel) {
//把当前通道的消息转发给选定通道的客户
uChannel.writeAndFlush("[客户]" + channel.remoteAddress() + "在 【" + sdf.format(new Date()) + "】 发送了消息:" + end[1] + " \n");
}
});
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//关闭通道
ctx.close();
System.out.println("在 【" + sdf.format(new Date()) + "】 关闭通道,客户总数:" + userChannels.size());
}
}
三、客户端代码
package com.tfq.netty.netty.personalchat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.Scanner;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
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;
/**
* @author: fqtang
* @date: 2024/04/04/7:54
* @description: 描述
*/
public class PersonChatClient {
private final String host;
private final int port;
public PersionChatClient(String host, int port) {
this.host = host;
this.port = port;
}
public void run() {
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventLoopGroup)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//得到pipeline
ChannelPipeline pipeline = ch.pipeline();
//加入相关handler的解码器
pipeline.addLast("decoder", new StringDecoder());
//加入相关handler的编码器
pipeline.addLast("encoder", new StringEncoder());
//加入自定义的handler
pipeline.addLast(new ChatClientHandler());
}
});
//连接服务器返回通道
ChannelFuture channelFuture = bootstrap.connect(host, port)
.sync();
Channel channel = channelFuture.channel();
if(channelFuture.isSuccess()) {
System.out.println("本地ip:"+channel.localAddress()+",连接服务器ip: "+channel.remoteAddress() + " 成功");
}
Scanner scanner = new Scanner(System.in);
while(scanner.hasNextLine()) {
channel.writeAndFlush(scanner.nextLine());
}
//给关闭监听进行通道
channel.closeFuture()
.sync();
} catch(InterruptedException e) {
throw new RuntimeException(e);
} finally {
eventLoopGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
new PersonChatClient("127.0.0.1", 7888).run();
}
}
客户端handler
package com.tfq.netty.netty.personalchat;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
/**
* @author: fqtang
* @date: 2024/04/04/8:16
* @description: 描述
*/
public class ChatClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println("收到服务器端转发的消息:"+msg.trim());
}
}
四、运行服务端程序(PersonChatServer.java)和客户端程序(PersonChatClient)
若大家运行有问题请留言。