客户端:
public class ChatClient {
public static void main(String[] args) {
//事件循环组
EventLoopGroup eventExecutors = new NioEventLoopGroup();
try {
//客户端的启动
Bootstrap bootstrap = new Bootstrap();
//处理事件,反射创建channel实例,处理的handler
bootstrap.group(eventExecutors).channel(NioSocketChannel.class).
handler(new ChatInitializer());
//绑定端口号
Channel channel = bootstrap.connect("127.0.0.1", 8991).sync().channel();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
channel.writeAndFlush(br.readLine() + "\r\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//异常发生退出
eventExecutors.shutdownGracefully();
}
}
}
public class ChatInitializer extends ChannelInitializer <SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
// pipeline.addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter()));
pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8), new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast(new ChatClientHandler());
}
}
public class ChatClientHandler extends SimpleChannelInboundHandler <String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(msg);
}
}
服务器:
public class ChatServer {
public static void main(String[] args) {
EventLoopGroup boosGrop = new NioEventLoopGroup();
EventLoopGroup workGrop = new NioEventLoopGroup();
ServerBootstrap serverBootstrap = new ServerBootstrap();
try {
serverBootstrap.group(boosGrop, workGrop).channel(NioServerSocketChannel.class).
childHandler(new ChatInitializer());
ChannelFuture channelFuture = serverBootstrap.bind(8991).sync();
ChannelFuture channelFuture1 = channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
boosGrop.shutdownGracefully();
workGrop.shutdownGracefully();
}
}
}
public class ChatInitializer extends ChannelInitializer <SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
// pipeline.addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter()));
pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8), new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast(new ChatHandler());
}
}
public class ChatHandler extends SimpleChannelInboundHandler <String> {
private static ChannelGroup CHANNELS = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
//转播消息
CHANNELS.forEach((t) -> {
if (!t.equals(ctx.channel())) {
t.writeAndFlush(LocalDateTime.now() + "\r\n" + msg);
} else {
t.writeAndFlush(LocalDateTime.now() + "[自己]" + "\r\n" + msg);
}
});
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
CHANNELS.writeAndFlush("时间" + LocalDateTime.now() + channel.remoteAddress() + "加入" + "\r\n");
CHANNELS.add(channel);
}
//自动触发channelGroup.remove方法
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
CHANNELS.writeAndFlush("时间" + LocalDateTime.now() + ctx.channel().remoteAddress() + "离开" + "\r\n");
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
CHANNELS.writeAndFlush("时间" + LocalDateTime.now() + ctx.channel().remoteAddress() + "上线" + "\r\n");
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
CHANNELS.writeAndFlush("时间" + LocalDateTime.now() + ctx.channel().remoteAddress() + "下线" + "\r\n");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}