实现逻辑:
1. 提供一个Netty服务端,用于接收客户端连接,消息以及消息分发;
2. 客户端用于接收消息,以及通过控制台发送消息(接收来自其他客户端发送的消息)
1. 引入netty依赖
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.42.Final</version>
</dependency>
2. 编写NettyChatServer类,开启服务端
public class NettyChatServer {
private int port;
public NettyChatServer(int port) {
this.port = port;
}
public static void main(String[] args) throws InterruptedException {
new NettyChatServer(8989).run();
}
public void run() throws InterruptedException {
EventLoopGroup bossGroup = null; // bossGroup 线程组,处理连接事件
EventLoopGroup workerGroup = null; // workerGroup线程组 处理读写事件
try {
bossGroup = new NioEventLoopGroup(1);
workerGroup = new NioEventLoopGroup(); // 默认线程数:2*处理器线程数
// 服务器启动助手
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup) // 设置bossGroup 以及workerGroup线程
.channel(NioServerSocketChannel.class) // 设置服务器通道实现为NIO
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE) // option 和 childOption区别在于 childOption是针对workerGroup线程组的操作
.childHandler(new ChannelInitializer<SocketChannel>() {// 创建通道初始化对象
protected void initChannel(SocketChannel ch) throws Exception {
// 向pipeline中添加String编码解码器
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new StringEncoder());
// 向pipeline中添加 服务端业务处理handler (编码解码器需要在业务类handler之前)
ch.pipeline().addLast(new NettyChatServerHandler());
}
});
// 绑定端口
ChannelFuture channelFuture = serverBootstrap.bind(port);
// ChannelFuture默认为异步,添加监听
channelFuture.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
System.out.println(port + " 端口绑定成功");
} else {
System.out.println(port + " 端口绑定失败");
}
}
});
System.out.println("聊天室服务端启动成功");
// 关闭对通道的监听
channelFuture.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
3. 编写NettyChatServerHandler消息处理handler
public class NettyChatServerHandler extends SimpleChannelInboundHandler<String> {
public static List<Channel> channelList = new ArrayList<Channel>();
/**
* 通道就绪事件
* @param ctx
* @throws Exception
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
System.out.println("[Server]:" + channel.remoteAddress().toString().substring(1) + " 在线");
channelList.add(channel);
}
/**
* 通道未就绪事件
* @param ctx
* @throws Exception
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
System.out.println("[Server]:" + channel.remoteAddress().toString().substring(1) + " 下线");
channelList.remove(channel);
}
/**
* 通道异常事件
* @param ctx
* @param cause
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
Channel channel = ctx.channel();
System.out.println("[Server]:" + channel.remoteAddress().toString().substring(1) + " 出现异常");
channelList.remove(channel);
}
/**
* 通道读取事件
* @param ctx
* @param msg
* @throws Exception
*/
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println("服务端接收到的 msg" + msg);
Channel channel = ctx.channel();
for (Channel channel1 : channelList) {
if (channel != channel1){
System.out.println(channel.remoteAddress().toString().substring(1) + ": " + msg);
channel1.writeAndFlush("[" + channel.remoteAddress().toString().substring(1) + "]: " + msg);
}
}
}
}
4. 服务端启动类NettyChatClient及对应的消息处理handler类NettyChatClientHandler
public class NettyChatClient {
private String ip;
private int port;
public NettyChatClient(String ip, int port) {
this.ip = ip;
this.port = port;
}
public static void main(String[] args) throws InterruptedException {
new NettyChatClient("127.0.0.1", 8989).run();
}
public void run() throws InterruptedException {
EventLoopGroup eventLoopGroup = null; // 线程组
try {
eventLoopGroup = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap(); //客户端启动助手
bootstrap.group(eventLoopGroup) // 设备线程组
.channel(NioSocketChannel.class) // 设置通道实现类为NioSocketChannel
.handler(new ChannelInitializer<SocketChannel>() {//创建通道初始化对象
protected void initChannel(SocketChannel ch) throws Exception {
// 向pipeline中添加String编码解码器
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new StringEncoder());
// 向pipeline中添加 客户端业务处理handler (编码解码器需要在业务类handler之前)
ch.pipeline().addLast(new NettyChatClientHandler());
}
});
// 启动客户端,连接服务端,将异步改为同步
ChannelFuture channelFuture = bootstrap.connect(ip, port).sync();
Channel channel = channelFuture.channel();
System.out.println("-----------" + channel.localAddress().toString().substring(1) + "--------------");
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()){
String msg = scanner.nextLine();
// System.out.println("msg: " + msg);
// 向服务端发送消息
channel.writeAndFlush(msg);
}
// 关闭通道
channelFuture.channel().closeFuture().sync();
}finally {
// 关闭 连接池
eventLoopGroup.shutdownGracefully();
}
}
}
public class NettyChatClientHandler extends SimpleChannelInboundHandler<String> {
/**
* 通道读取就绪事件
* @param ctx
* @param msg
* @throws Exception
*/
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(msg);
}
}
测试验证:启动NettyChatServer服务端,启动多个客户端NettyChatClient,在客户端控制台进行消息发送