概念
Server
【Server】
package com.artisan.talk; 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 小工匠 * @version 1.0 * @mark: show me the code , change the world */ public class TalkRoomServer { public static void main(String[] args) throws InterruptedException { // 主Reactor 如果这里的线程是多个,则说明 需要监听多个端口,这里设置为1 EventLoopGroup bossGroup = new NioEventLoopGroup(1); // 从Reactor EventLoopGroup workerGroup = new NioEventLoopGroup(8); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); //向pipeline加入解码器 pipeline.addLast("decoder", new StringDecoder()); //向pipeline加入编码器 pipeline.addLast("encoder", new StringEncoder()); //加入自己的业务处理handler pipeline.addLast(new TalkRoomServerHandler()); } }); ChannelFuture channelFuture = bootstrap.bind(1234).sync(); System.out.println("Talk Room Server启动成功,监听1234端口"); //关闭通道 channelFuture.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }
【ServerHandler】
package com.artisan.talk; 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; import java.text.SimpleDateFormat; /** * @author 小工匠 * @version 1.0 * @mark: show me the code , change the world */ public class TalkRoomServerHandler extends SimpleChannelInboundHandler<String> { /** * GlobalEventExecutor.INSTANCE 是全局的事件执行器,是一个单例 */ private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); /** * 先忽略线程安全问题, 仅Demo使用 */ private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /** * 表示 channel 处于就绪状态, 提示上线 * * @param ctx */ @Override public void channelActive(ChannelHandlerContext ctx) { Channel channel = ctx.channel(); //将该客户加入聊天的信息推送给其它在线的客户端 //该方法会将 channelGroup 中所有的 channel 遍历,并发送消息 channelGroup.writeAndFlush("[ 客户端 ]" + channel.remoteAddress() + " 上线了 " + sdf.format(new java.util.Date()) + "\n"); //将当前 channel 加入到 channelGroup channelGroup.add(channel); System.out.println(ctx.channel().remoteAddress() + " 上线了" + "\n"); } /** * 表示 channel 处于不活动状态, 提示离线了 * * @param ctx */ @Override public void channelInactive(ChannelHandlerContext ctx) { Channel channel = ctx.channel(); //将客户离开信息推送给当前在线的客户 channelGroup.writeAndFlush("[ 客户端 ]" + channel.remoteAddress() + " 下线了" + "\n"); System.out.println(ctx.channel().remoteAddress() + " 下线了" + "\n"); System.out.println("channelGroup size=" + channelGroup.size()); } /** * 读取数据 * * @param ctx the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler} * belongs to * @param msg the message to handle */ @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) { //获取到当前 channel Channel channel = ctx.channel(); //这时我们遍历 channelGroup, 根据不同的情况, 回送不同的消息 channelGroup.forEach(ch -> { if (channel != ch) { //不是当前的 channel,转发消息 ch.writeAndFlush("[ 客户端 ]" + channel.remoteAddress() + " 发送了消息:" + msg + "\n"); } else {//回显自己发送的消息给自己 ch.writeAndFlush("[ 自己 ]发送了消息:" + msg + "\n"); } }); } /** * 异常处理 * * @param ctx * @param cause */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { //这里简单处理:关闭通道 ctx.close(); } }
Client
【Client】
package com.artisan.talk; 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; import java.util.Scanner; /** * @author 小工匠 * @version 1.0 * @mark: show me the code , change the world */ public class TalkRoomClient { public static void main(String[] args) throws InterruptedException { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); //向pipeline加入解码器 pipeline.addLast("decoder", new StringDecoder()); //向pipeline加入编码器 pipeline.addLast("encoder", new StringEncoder()); //加入自己的业务处理handler pipeline.addLast(new TalkRoomClientHandler()); } }); ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 1234).sync(); //得到 channel Channel channel = channelFuture.channel(); System.out.println("========" + channel.localAddress() + "========"); //客户端需要输入信息, 创建一个扫描器 Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) { String msg = scanner.nextLine(); //通过 channel 发送到服务器端 channel.writeAndFlush(msg); } } finally { group.shutdownGracefully(); } } }
【ClientHandler】
package com.artisan.talk; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; /** * @author 小工匠 * @version 1.0 * @mark: show me the code , change the world */ public class TalkRoomClientHandler extends SimpleChannelInboundHandler<String> { /** * * @param ctx the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler} * belongs to * @param msg the message to handle */ @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) { System.out.println("收到消息->" + msg.trim()); } }
测试
启动Server,启动多个Client
上线
发送消息
断开连接