netty-第一个案例

刺骨的言语ヽ痛彻心扉 2023-06-08 06:21 18阅读 0赞

netty-第一个demo

netty

搭建环境

maven引入

  1. <dependency>
  2. <groupId>io.netty</groupId>
  3. <artifactId>netty-all</artifactId>
  4. <version>4.1.12.Final</version>
  5. </dependency>

服务端

Netty 服务器都需要以下两部分

  • 至少一个 ChannelHandler — 该组件实现了服务器对从客户端接收的数据的处理,即它的业务逻辑。
  • 引导 — 这是配置服务器的启动代码。至少,它会将服务器绑定到它要监听连接请求的端口上

channelHandler

  1. @Sharable
  2. public class EchoServerHandler extends ChannelInboundHandlerAdapter {
  3. // 对于每个传入的消息都要调用
  4. @Override
  5. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  6. ByteBuf in = (ByteBuf) msg;
  7. System.out.println("server recevied:"+ in.toString(StandardCharsets.UTF_8));
  8. ctx.write(in);
  9. }
  10. // 通知ChannelInboundHandler最后一次对channel-
  11. //Read()的调用是当前批量读取中的最后一条消息
  12. @Override
  13. public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
  14. ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
  15. }
  16. // 在读取操作期间,有异常抛出时会调用
  17. @Override
  18. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  19. System.out.println("读取操作错误信息");
  20. cause.printStackTrace(); //打印错误
  21. ctx.close();//关闭channel
  22. }
  23. }

BootStrap

  1. public class EchoServer {
  2. private final int port;
  3. public EchoServer(int port) {
  4. this.port = port;
  5. }
  6. public static void main(String[] args) throws InterruptedException {
  7. int port = Integer.parseInt("1234");
  8. new EchoServer(port).start();
  9. }
  10. //绑定到服务器将在其上监听并接受传入连接请求的端口;
  11. //配置 Channel ,以将有关的入站消息通知给 EchoServerHandler 实例
  12. private void start() throws InterruptedException {
  13. final EchoServerHandler serverHandler = new EchoServerHandler();
  14. NioEventLoopGroup group = new NioEventLoopGroup();
  15. try {
  16. ServerBootstrap b = new ServerBootstrap(); //创建bootstrap
  17. b.group(group)
  18. .channel(NioServerSocketChannel.class) //使用nio传输channel
  19. .localAddress(port) // 绑定端口
  20. .childHandler(new ChannelInitializer<SocketChannel>() {
  21. // 添加一个EchoServer-
  22. //Handler 到子Channel
  23. //的 ChannelPipeline
  24. @Override
  25. protected void initChannel(SocketChannel ch) throws Exception {
  26. ch.pipeline().addLast(serverHandler);
  27. // EchoServerHandler被标注为@Shareable,所以我们可以总是使用同样的实例
  28. }
  29. });
  30. // 异步地绑定服务器;调用 sync()方法阻塞等待直到绑定完成
  31. ChannelFuture f = b.bind().sync();
  32. // 获取 Channel 的CloseFuture,并且阻塞当前线程直到它完成
  33. f.channel().closeFuture().sync();
  34. } catch (InterruptedException e) {
  35. e.printStackTrace();
  36. }finally {
  37. group.shutdownGracefully().sync();
  38. }
  39. }
  40. }

客户端

EchoClientHandler

  1. @Sharable
  2. public class EchoClientHandler
  3. extends SimpleChannelInboundHandler<ByteBuf> {
  4. @Override
  5. public void channelActive(ChannelHandlerContext ctx) {
  6. ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!",
  7. CharsetUtil.UTF_8));
  8. }
  9. @Override
  10. public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) {
  11. System.out.println(
  12. "Client received: " + in.toString(CharsetUtil.UTF_8));
  13. }
  14. @Override
  15. public void exceptionCaught(ChannelHandlerContext ctx,
  16. Throwable cause) {
  17. cause.printStackTrace();
  18. ctx.close();
  19. }
  20. }

BootStrap

  1. public class EchoClient {
  2. private final String host;
  3. private final int port;
  4. public EchoClient(String host, int port) {
  5. this.host = host;
  6. this.port = port;
  7. }
  8. public static void main(String[] args) throws InterruptedException {
  9. final String host = "127.0.0.1";
  10. final int port = Integer.parseInt("1234");
  11. new EchoClient(host, port).start();
  12. }
  13. private void start() throws InterruptedException {
  14. NioEventLoopGroup group = new NioEventLoopGroup();
  15. try {
  16. Bootstrap b = new Bootstrap();
  17. b.group(group)
  18. .channel(NioSocketChannel.class)
  19. .remoteAddress(host,port)
  20. .handler(new ChannelInitializer<SocketChannel>() {
  21. @Override
  22. protected void initChannel(SocketChannel ch) throws Exception {
  23. ch.pipeline().addLast(new EchoClientHandler());
  24. }
  25. });
  26. ChannelFuture future = b.connect().sync();
  27. future.channel().closeFuture().sync();
  28. } catch (InterruptedException e) {
  29. e.printStackTrace();
  30. }finally {
  31. group.shutdownGracefully().sync();
  32. }
  33. }
  34. }

运行

  • 先启动服务端
  • 再启动客户端

服务端结果

  1. server recevied:Netty Socket!

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NoEjY2Eb-1571234128207)(C:\Users\ronny\OneDrive\笔记\高并发\picture\1571232070255.png)]

参考文档

[Netty 拆包粘包和服务启动流程分析](https://segmentfault.com/a/1190000013039327)

Netty序章之BIO NIO AIO演变

java nio与bio —— 阻塞IO与非阻塞IO的区别

Java实战之从同步阻塞IO到NIO

netty实战

发表评论

表情:
评论列表 (有 0 条评论,18人围观)

还没有评论,来说两句吧...

相关阅读