【Netty】读书笔记 - 跟闪电侠学netty

1. 内容概要

1.1 本节实现功能

  • 客户端:连接服务器,之后向服务器发送数据
  • 服务端:接收数据后打印,并向客户端发送数据

1.2 本节知识点

1.2.1 ch.pipeline().addLast(new FirstClientHandler());

  • 责任链模式:ch.pipeline()
  • 添加处理逻辑:addLast()

1.2.2 继承 extends ChannelInboundHandlerAdapter

  • 客户端:覆盖channelActive()方法,客户端连接成功时被调用
  • 服务器:覆盖channelRead()方法,接收到客户端发送的数据时被调用

1.2.3 创建ByteBuf并写入数据

    private ByteBuf getByteBuf(ChannelHandlerContext ctx) {byte[] bytes = "你好,闪电侠!".getBytes(Charset.forName("utf-8"));ByteBuf buffer = ctx.alloc().buffer();buffer.writeBytes(bytes);return buffer;}

1.2.4 channelRead中Object msg转ByteBuf

  • ByteBuf byteBuf = (ByteBuf) msg;

1.2.5 ctx.channel().writeAndFlush(buffer)

  • ​​​​​​​ctx.channel():获取ByteBuf的内存管理器
  • writeAndFlush():写数据并发送(到服务器/客户端)

2 客户端

  • NettyClient
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;import java.util.Date;
import java.util.concurrent.TimeUnit;public class NettyClient {private static final int MAX_RETRY = 5;private static final String HOST = "127.0.0.1";private static final int PORT = 8000;public static void main(String[] args) {NioEventLoopGroup workerGroup = new NioEventLoopGroup();Bootstrap bootstrap = new Bootstrap();bootstrap.group(workerGroup).channel(NioSocketChannel.class).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000).option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {@Overridepublic void initChannel(SocketChannel ch) {ch.pipeline().addLast(new FirstClientHandler());}});connect(bootstrap, HOST, PORT, MAX_RETRY);}private static void connect(Bootstrap bootstrap, String host, int port, int retry) {bootstrap.connect(host, port).addListener(future -> {if (future.isSuccess()) {System.out.println("连接成功!");} else if (retry == 0) {System.err.println("重试次数已用完,放弃连接!");} else {// 第几次重连int order = (MAX_RETRY - retry) + 1;// 本次重连的间隔int delay = 1 << order;System.err.println(new Date() + ": 连接失败,第" + order + "次重连……");bootstrap.config().group().schedule(() -> connect(bootstrap, host, port, retry - 1), delay, TimeUnit.SECONDS);}});}
}
  • FirstClientHandler:客户端器逻辑处理类
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;import java.nio.charset.Charset;
import java.util.Date;public class FirstClientHandler extends ChannelInboundHandlerAdapter {@Overridepublic void channelActive(ChannelHandlerContext ctx) {System.out.println(new Date() + ": 客户端写出数据");// 1.获取数据ByteBuf buffer = getByteBuf(ctx);// 2.写数据ctx.channel().writeAndFlush(buffer);}private ByteBuf getByteBuf(ChannelHandlerContext ctx) {byte[] bytes = "你好,闪电侠!".getBytes(Charset.forName("utf-8"));ByteBuf buffer = ctx.alloc().buffer();buffer.writeBytes(bytes);return buffer;}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) {ByteBuf byteBuf = (ByteBuf) msg;System.out.println(new Date() + ": 客户端读到数据 -> " + byteBuf.toString(Charset.forName("utf-8")));}
}

3 服务端

  • NettyServer
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;public class NettyServer {private static final int PORT = 8000;public static void main(String[] args) {NioEventLoopGroup boosGroup = new NioEventLoopGroup();NioEventLoopGroup workerGroup = new NioEventLoopGroup();final ServerBootstrap serverBootstrap = new ServerBootstrap();serverBootstrap.group(boosGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024).childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.TCP_NODELAY, true).childHandler(new ChannelInitializer<NioSocketChannel>() {protected void initChannel(NioSocketChannel ch) {ch.pipeline().addLast(new FirstServerHandler());}});bind(serverBootstrap, PORT);}private static void bind(final ServerBootstrap serverBootstrap, final int port) {serverBootstrap.bind(port).addListener(future -> {if (future.isSuccess()) {System.out.println("端口[" + port + "]绑定成功!");} else {System.err.println("端口[" + port + "]绑定失败!");}});}
}
  • FirstServerHandler:服务器逻辑处理类
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;import java.nio.charset.Charset;
import java.util.Date;public class FirstServerHandler extends ChannelInboundHandlerAdapter {@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) {ByteBuf byteBuf = (ByteBuf) msg;System.out.println(new Date() + ": 服务端读到数据 -> " + byteBuf.toString(Charset.forName("utf-8")));// 回复数据到客户端System.out.println(new Date() + ": 服务端写出数据");ByteBuf out = getByteBuf(ctx);ctx.channel().writeAndFlush(out);}private ByteBuf getByteBuf(ChannelHandlerContext ctx) {byte[] bytes = "你好,欢迎关注我的微信公众号,《闪电侠的博客》!".getBytes(Charset.forName("utf-8"));ByteBuf buffer = ctx.alloc().buffer();buffer.writeBytes(bytes);return buffer;}
}

【闪电侠学netty】第6章 客户端与服务端双向通信相关推荐

  1. Netty实战 IM即时通讯系统(六)实战: 客户端和服务端双向通信

    ## Netty实战 IM即时通讯系统(六)实战: 客户端和服务端双向通信 零. 目录 IM系统简介 Netty 简介 Netty 环境配置 服务端启动流程 实战: 客户端和服务端双向通信 数据传输载 ...

  2. 【初识Netty使用Netty实现简单的客户端与服务端的通信操作Netty框架中一些重要的类以及方法的解析】

    一.Netty是什么? Netty 由 Trustin Lee(韩国,Line 公司)2004 年开发 本质:网络应用程序框架 实现:异步.事件驱动 特性:高性能.可维护.快速开发 用途:开发服务器和 ...

  3. 【闪电侠学netty】第8章 客户端与服务端通信协议编解码

    [Netty]读书笔记 - 跟闪电侠学 1. 内容概要 1.1 总结 1.1.1 编码与解码定义 编码:把java对象根据协议封装成二进制数据包的过程 解码:从二进制数据包中解析出Java对象的过程 ...

  4. 学游戏开发,从客户端还是服务端开始?

    ##前言 近几年,游戏开发行业风生水起,入行的个个都赚个盆满钵满,这种现状反过来又吸引着更多人源源不断地进行这个行业. 那么,对于刚刚转行到游戏开发或者有意转行的朋友来说,应该从哪里开始学起呢? 这个 ...

  5. 【Netty】读书笔记 - 跟闪电侠学netty

    前言:本篇只是笔者的读书总结,推荐结合原书观看(推荐指数:5星) 上篇 入门实战 第1章 即时聊天系统简介 第2章 Netty是什么 第3章 Netty开发环境配置 第4章 服务端启动流程 第5章 客 ...

  6. Netty实战 IM即时通讯系统(十)实现客户端和服务端收发消息

    Netty实战 IM即时通讯系统(十)实现客户端和服务端收发消息 零. 目录 IM系统简介 Netty 简介 Netty 环境配置 服务端启动流程 客户端启动流程 实战: 客户端和服务端双向通信 数据 ...

  7. Netty实战 IM即时通讯系统(十二)构建客户端与服务端pipeline

    Netty实战 IM即时通讯系统(十二)构建客户端与服务端pipeline 零. 目录 IM系统简介 Netty 简介 Netty 环境配置 服务端启动流程 客户端启动流程 实战: 客户端和服务端双向 ...

  8. Netty简单实现客户端与服务端收发消息

    Netty简单实现客户端与服务端收发消息 这个小案例主要是实现netty收发消息,分为客户端,及服务端,以及包含了相关状态处理,主要的代码会放在最后 gitHub 地址上,有需要可以看一下 首先来简单 ...

  9. 【闪电侠学netty】第1章 即时聊天系统简介

    [Netty]读书笔记 - 跟闪电侠学 1. 内容概要 1.1 单聊流程图 1.2 单聊的指令流程图+指令集 1.3 群聊流程图 1.4 群聊的指令流程图+指令集 1.5 Netty核心知识点+客户端 ...

最新文章

  1. Windows Server 2008 下ASP程序连接ORACLE数据库驱动错误
  2. python中编写函数素数_如何用Python编写素数程序?
  3. Android MVVM封装,MVVMFramework
  4. LeetCode-726. 原子的数量(python2)
  5. 求两数最大公约数,最小公倍数-Java
  6. linux 下orapwd 未找到命令,关于orapwd命令entries参数的探究
  7. Plupload文件上传组件使用API
  8. Rust 逆袭!位列 Stack Overflow 2018 最受欢迎编程语言榜首
  9. UTF-8与GB2312之间的互换
  10. python输入一个整数、输出该整数的所有素数因子_【401】Python 求合数的所有质数因子...
  11. java图形用户界面实验_java图形用户界面实验教程
  12. Windows XP优化设置之网络篇
  13. php gmssl,GmSSL是什么
  14. 《SPSS统计分析与行业应用实战》之诊断试验与ROC分析
  15. pe linux镜像,pe启动镜像img
  16. 多目标蚁群算法路径规划(一)-----从数据设计到毕业论文系列
  17. 无线量子通信/无线量子通讯,5G下一代物联网的创新研究
  18. Vue template挂载中el和mouted的使用和区别
  19. AI生成新春祝福海报,AIGC从“炫技”走向日常
  20. 入职一家初创公司第一周的血与泪

热门文章

  1. “由于 open 函数中有时间冲突,WMI ADAP 无法处理 RemoteAccess 性能库”。
  2. Google Baidu 和 Yahoo 搜索PK
  3. Creator3D:shader9_这样的内发光你喜欢不
  4. 阅读笔记-Modulation and Coding Design for Simultaneous Wireless Information and Power Transfer
  5. 51nod 1414 冰雕【思维+暴力】
  6. 利用genedoc绘制一张多序列比对图
  7. ubuntu 系统配置网卡
  8. 天地伟业tiandy如何连手机_天地伟业安卓版下载-天地伟业app官方下载v4.1.3[视频监控]...
  9. 在线考试系统数据库设计
  10. 最新2023基于微信小程序的服装企业人事OA管理系统+后台管理系统(Springboot+mysql)-JAVA.VUE(毕业设计+论文+开题报告+运行)