package com.lglbc.day2; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; 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.util.CharsetUtil; import lombok.extern.slf4j.Slf4j; import java.util.Arrays; /** * @Description TODO * @Author 乐哥聊编程 * @Date 2022/12/3 12:55 */ public class NettyClient { 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 { ch.pipeline().addLast(new NettyClientHandler()); //加入自己的处理器 } }); System.out.println("客户端 ok.."); ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 9999).sync(); //给关闭通道进行监听 channelFuture.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } } @Slf4j class NettyClientHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) { for (int i=0;i<10;i++) { byte[] bytes = new byte[102400]; Arrays.fill(bytes, (byte) 10); // ctx.writeAndFlush(Unpooled.copiedBuffer(bytes)); ctx.writeAndFlush(Unpooled.copiedBuffer("服务端你好:我和你建立连接了", CharsetUtil.UTF_8)); } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf byteBuf = (ByteBuf) msg; log.info("收到服务端消息:{}", byteBuf.toString(CharsetUtil.UTF_8)); } }
package com.lglbc.day2; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; 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.util.CharsetUtil; import lombok.extern.flogger.Flogger; import lombok.extern.slf4j.Slf4j; @Slf4j public class NettyServer { public static void main(String[] args) throws InterruptedException { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); //8 try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.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 { log.info("客户端channel 初始化"); ch.pipeline().addLast(new NettyServerHandler()); } }); ChannelFuture cf = bootstrap.bind(9999).sync(); log.info("服务启动成功...."); cf.addListener((ChannelFutureListener) future -> log.info("监听端口:{}",future.isSuccess())); cf.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } } @Slf4j class NettyServerHandler extends ChannelInboundHandlerAdapter { int i=0; @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf byteBuf = (ByteBuf) msg; log.info("第{}次收到客户端消息:{}\n",i++,byteBuf.readableBytes()); // 现在通过通道给客户端回消息 // ctx.writeAndFlush(Unpooled.copiedBuffer("客户端你好:我收到你的消息了", CharsetUtil.UTF_8)); } @Override public void channelReadComplete(ChannelHandlerContext ctx) { } } day2
package com.lglbc.day6.fixedlength; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; 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.util.CharsetUtil; import lombok.extern.slf4j.Slf4j; import java.io.UnsupportedEncodingException; import java.util.Arrays; /** * @Description TODO * @Author 乐哥聊编程 * @Date 2022/12/3 12:55 */ public class NettyClient { 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 { ch.pipeline().addLast(new NettyClientHandler()); //加入自己的处理器 } }); System.out.println("客户端 ok.."); ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 9999).sync(); //给关闭通道进行监听 channelFuture.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } } @Slf4j class NettyClientHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) { for (int i=0;i<9;i++) { String reqMsg = (i + 1) + "我是客户端"; byte[] reqMsgByte = new byte[0]; try { reqMsgByte = reqMsg.getBytes("UTF-8"); ByteBuf reqByteBuf = Unpooled.buffer(reqMsgByte.length); System.out.println(reqMsgByte.length); reqByteBuf.writeBytes(reqMsgByte); ctx.writeAndFlush(reqByteBuf); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf byteBuf = (ByteBuf) msg; log.info("收到服务端消息:{}", byteBuf.toString(CharsetUtil.UTF_8)); } }
package com.lglbc.day6.fixedlength; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBuf; 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.FixedLengthFrameDecoder; import lombok.extern.slf4j.Slf4j; /** * @Description TODO * @Author 乐哥聊编程 * @Date 2022/12/3 12:34 */ @Slf4j public class NettyServer { public static void main(String[] args) throws InterruptedException { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); //8 try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.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 { log.info("客户端channel 初始化"); ch.pipeline().addLast(new FixedLengthFrameDecoder(16)); ch.pipeline().addLast(new NettyServerHandler()); } }); ChannelFuture cf = bootstrap.bind(9999).sync(); log.info("服务启动成功...."); cf.addListener((ChannelFutureListener) future -> log.info("监听端口:{}",future.isSuccess())); cf.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } } @Slf4j class NettyServerHandler extends ChannelInboundHandlerAdapter { int i=0; @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf byteBuf = (ByteBuf) msg; log.info("第{}次收到客户端消息:{}\n",i++,byteBuf.readableBytes()); } @Override public void channelReadComplete(ChannelHandlerContext ctx) { } }
day3
package com.lglbc.day6.line; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; 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.util.CharsetUtil; import lombok.extern.slf4j.Slf4j; import java.io.UnsupportedEncodingException; /** * @Description TODO * @Author 乐哥聊编程 * @Date 2022/12/3 12:55 */ public class NettyClient { 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 { ch.pipeline().addLast(new NettyClientHandler()); //加入自己的处理器 } }); System.out.println("客户端 ok.."); ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 9999).sync(); //给关闭通道进行监听 channelFuture.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } } @Slf4j class NettyClientHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) { for (int i=0;i<9;i++) { String reqMsg = (i + 1) + "我是客户端\n\r"; byte[] reqMsgByte = new byte[0]; try { reqMsgByte = reqMsg.getBytes("UTF-8"); ByteBuf reqByteBuf = Unpooled.buffer(reqMsgByte.length); reqByteBuf.writeBytes(reqMsgByte); ctx.writeAndFlush(reqByteBuf); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf byteBuf = (ByteBuf) msg; log.info("收到服务端消息:{}", byteBuf.toString(CharsetUtil.UTF_8)); } }
package com.lglbc.day6.line; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBuf; 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.LineBasedFrameDecoder; import lombok.extern.slf4j.Slf4j; /** * @Description TODO * @Author 乐哥聊编程 * @Date 2022/12/3 12:34 */ @Slf4j public class NettyServer { public static void main(String[] args) throws InterruptedException { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); //8 try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.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 { log.info("客户端channel 初始化"); ch.pipeline().addLast(new LineBasedFrameDecoder(1024)); ch.pipeline().addLast(new NettyServerHandler()); } }); ChannelFuture cf = bootstrap.bind(9999).sync(); log.info("服务启动成功...."); cf.addListener((ChannelFutureListener) future -> log.info("监听端口:{}",future.isSuccess())); cf.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } } @Slf4j class NettyServerHandler extends ChannelInboundHandlerAdapter { int i=0; @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf byteBuf = (ByteBuf) msg; log.info("第{}次收到客户端消息:{}\n",i++,byteBuf.readableBytes()); } @Override public void channelReadComplete(ChannelHandlerContext ctx) { } }
day4
package com.lglbc.day6.split; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; 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.util.CharsetUtil; import lombok.extern.slf4j.Slf4j; import java.io.UnsupportedEncodingException; /** * @Description TODO * @Author 乐哥聊编程 * @Date 2022/12/3 12:55 */ public class NettyClient { 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 { ch.pipeline().addLast(new NettyClientHandler()); //加入自己的处理器 } }); System.out.println("客户端 ok.."); ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 9999).sync(); //给关闭通道进行监听 channelFuture.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } } @Slf4j class NettyClientHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) { for (int i=0;i<9;i++) { String reqMsg = (i + 1) + "我是客户端lglbc"; byte[] reqMsgByte = new byte[0]; try { reqMsgByte = reqMsg.getBytes("UTF-8"); ByteBuf reqByteBuf = Unpooled.buffer(reqMsgByte.length); reqByteBuf.writeBytes(reqMsgByte); ctx.writeAndFlush(reqByteBuf); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf byteBuf = (ByteBuf) msg; log.info("收到服务端消息:{}", byteBuf.toString(CharsetUtil.UTF_8)); } }
package com.lglbc.day6.split; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; 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.DelimiterBasedFrameDecoder; import io.netty.handler.codec.LineBasedFrameDecoder; import lombok.extern.slf4j.Slf4j; /** * @Description TODO * @Author 乐哥聊编程 * @Date 2022/12/3 12:34 */ @Slf4j public class NettyServer { public static void main(String[] args) throws InterruptedException { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); //8 try { log.info("演示撤销commit的内容"); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.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 { log.info("客户端channel 初始化"); ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, Unpooled.wrappedBuffer("lglbc".getBytes()))); ch.pipeline().addLast(new NettyServerHandler()); } }); ChannelFuture cf = bootstrap.bind(9999).sync(); log.info("服务启动成功...."); cf.addListener((ChannelFutureListener) future -> log.info("监听端口:{}",future.isSuccess())); cf.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } } @Slf4j class NettyServerHandler extends ChannelInboundHandlerAdapter { int i=0; @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf byteBuf = (ByteBuf) msg; log.info("第{}次收到客户端消息:{}\n",i++,byteBuf.readableBytes()); } @Override public void channelReadComplete(ChannelHandlerContext ctx) { } } 自定义
package com.lglbc.day6.custom; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; 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.util.CharsetUtil; import lombok.extern.slf4j.Slf4j; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; /** * @Description TODO * @Author 乐哥聊编程 * @Date 2022/12/3 12:55 */ public class NettyClient { 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 { ch.pipeline().addLast(new NettyMsgEncoder()); //加入自定义编码处理器 ch.pipeline().addLast(new NettyClientHandler()); //加入自己的处理器 } }); System.out.println("客户端 ok.."); ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 9999).sync(); //给关闭通道进行监听 channelFuture.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } } @Slf4j class NettyClientHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) { for (int i=0;i<10;i++) { NettyMsg msg = new NettyMsg(); msg.setContent("我是乐哥聊编程,我在使用自定义编解码器 解决拆包和粘包的问题".getBytes(StandardCharsets.UTF_8)); msg.setLen(msg.getContent().length); ctx.writeAndFlush(msg); } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf byteBuf = (ByteBuf) msg; log.info("收到服务端消息:{}", byteBuf.toString(CharsetUtil.UTF_8)); } }
package com.lglbc.day6.custom; /** * @Description TODO * @Author 乐哥聊编程 * @Date 2022/12/10 09:58 */ public class NettyMsg { private int len; private byte[] content; public int getLen() { return len; } public void setLen(int len) { this.len = len; } public byte[] getContent() { return content; } public void setContent(byte[] content) { this.content = content; } }
package com.lglbc.day6.custom; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.MessageToByteEncoder; import lombok.extern.slf4j.Slf4j; import java.util.List; /** * @Description TODO * @Author 乐哥聊编程 * @Date 2022/12/10 10:00 */ @Slf4j public class NettyMsgDecoder extends ByteToMessageDecoder { int length=0; @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (in.readableBytes()>4){ if(length==0){ length=in.readInt(); } if(in.readableBytes()<length){ log.info("长度不够,继续等待"); return; } byte[] content=new byte[length]; in.readBytes(content); NettyMsg message=new NettyMsg(); message.setLen(length); message.setContent(content); // 发送给下一个handler out.add(message); length=0; } } }
package com.lglbc.day6.custom; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; import io.netty.handler.timeout.IdleStateHandler; /** * @Description TODO * @Author 乐哥聊编程 * @Date 2022/12/10 10:00 */ public class NettyMsgEncoder extends MessageToByteEncoder<NettyMsg> { @Override protected void encode(ChannelHandlerContext ctx, NettyMsg msg, ByteBuf out) throws Exception { out.writeInt(msg.getLen()); out.writeBytes(msg.getContent()); } }
package com.lglbc.day6.custom; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; 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.DelimiterBasedFrameDecoder; import lombok.extern.slf4j.Slf4j; import java.nio.charset.StandardCharsets; /** * @Description TODO * @Author 乐哥聊编程 * @Date 2022/12/3 12:34 */ @Slf4j public class NettyServer { public static void main(String[] args) throws InterruptedException { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); //8 try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.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 { ch.pipeline().addLast(new NettyMsgDecoder()); //加入自定义解码处理器 ch.pipeline().addLast(new NettyServerHandler()); } }); ChannelFuture cf = bootstrap.bind(9999).sync(); log.info("服务启动成功...."); cf.addListener((ChannelFutureListener) future -> log.info("监听端口:{}",future.isSuccess())); cf.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } } @Slf4j class NettyServerHandler extends SimpleChannelInboundHandler<NettyMsg> { int i=0; @Override protected void channelRead0(ChannelHandlerContext ctx, NettyMsg msg) throws Exception { log.info("第{}次收到客户端消息:{}\n",i++,new String(msg.getContent(), StandardCharsets.UTF_8)); } @Override public void channelReadComplete(ChannelHandlerContext ctx) { } }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.lglbc</groupId> <artifactId>Netty</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.21</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.22</version> </dependency> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.4.1</version> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.18.Final</version> </dependency> </dependencies> </project>