Netty实现群聊demo
一、pom引入
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.42.Final</version>
</dependency>
二、服务端
1、服务端启动类
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import java.awt.*;
public class GroupChatServer {
private int port;
public GroupChatServer(int port) {
this.port = port;
}
public void run() {
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new GroupChatServerChannelInitializer());
System.out.println("群聊服务器启动...");
try {
ChannelFuture channelFuture = serverBootstrap.bind(6666).sync();
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
new GroupChatServer(6666).run();
}
}
2、服务端通道配置类
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
public class GroupChatServerChannelInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline channelPipeline = socketChannel.pipeline();
channelPipeline.addLast("stringDecoder",new StringDecoder());
channelPipeline.addLast("stringEncoder",new StringEncoder());
channelPipeline.addLast("groupChatServerInputMessageHandler",new GroupChatServerInputMessageHandler());
}
}
3、服务端信息处理类
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.EventExecutor;
import io.netty.util.concurrent.GlobalEventExecutor;
import java.text.SimpleDateFormat;
import java.util.Date;
public class GroupChatServerInputMessageHandler extends SimpleChannelInboundHandler<String> {
private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("["+simpleDateFormat.format(new Date())+"][客户端][" + ctx.channel().remoteAddress() + "]——上线");
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("["+simpleDateFormat.format(new Date())+"][客户端][" + ctx.channel().remoteAddress() + "]——下线");
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
channelGroup.writeAndFlush("["+simpleDateFormat.format(new Date())+"][客户端][" + channel.remoteAddress() + "]——加入聊天\n");
channelGroup.add(channel);
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
channelGroup.writeAndFlush("["+simpleDateFormat.format(new Date())+"][客户端][" + channel.remoteAddress() + "]——离开聊天\n");
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
Channel channel = ctx.channel();
channelGroup.forEach(c -> {
if (channel != c){
c.writeAndFlush("["+simpleDateFormat.format(new Date())+"][客户端][" + channel.remoteAddress() + "]:" + msg + "\n");
}else{
c.writeAndFlush("["+simpleDateFormat.format(new Date())+"][自己]" + ":" + msg + "\n");
}
});
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
}
}
三、客户端
1、客户端启动类
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.util.Scanner;
public class GroupChatClient {
private final String host;
private final int port;
public GroupChatClient(String host, int port) {
this.host = host;
this.port = port;
}
public void run() {
NioEventLoopGroup eventLoop = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
try {
bootstrap.group(eventLoop)
.channel(NioSocketChannel.class)
.handler(new GroupChatClientChannelInitializer());
ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
Channel channel = channelFuture.channel();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String msg = scanner.nextLine();
if (msg.equals("exit")) {
break;
}
channel.writeAndFlush(msg + "\r\n");
}
channel.closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
eventLoop.shutdownGracefully();
}
}
public static void main(String[] args) {
new GroupChatClient("127.0.0.1",6666).run();
}
}
2、客户端通道配置类
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
public class GroupChatClientChannelInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline channelPipeline = socketChannel.pipeline();
channelPipeline.addLast("stringDecoder",new StringDecoder());
channelPipeline.addLast("stringEncoder",new StringEncoder());
channelPipeline.addLast("groupChatClientInputMessageHandler",new GroupChatClientInputMessageHandler());
}
}
3、客户端信息处理类
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
public class GroupChatClientInputMessageHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(msg.trim());
}
}
四、运行截图
1、服务端
2、客户端1
3、客户端2
4、客户端3