可参考博客:http://ifeve.com/netty5-user-guide/


Server类:

package com.zyh.study.netty.helloworld;import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
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.NioServerSocketChannel;/*** @Description:* @Author: zyh* @Date: created in 2018/7/22*/
public class Server {public static void main(String[] args) throws Exception {//用于处理服务器端接受客户端连接的线程组NioEventLoopGroup bossGroup = new NioEventLoopGroup();//用于进行网络通讯(读写)的线程组NioEventLoopGroup workGroup = new NioEventLoopGroup();//创建辅助工具类,用于服务器通道的一系列的配置ServerBootstrap sb = new ServerBootstrap();sb.group(bossGroup,workGroup)//绑定两个线程组.channel(NioServerSocketChannel.class)//指定NIO的网络传输模式为TCP,UDP:NioDatagramChannel.option(ChannelOption.SO_BACKLOG,1024)//设置tcp缓冲.option(ChannelOption.SO_SNDBUF,32*1024)//设置发送缓冲大小.option(ChannelOption.SO_RCVBUF,32*1024)//设置接收缓冲大小.option(ChannelOption.SO_KEEPALIVE,true)//保持连接.childHandler(new ChannelInitializer<SocketChannel>() {protected void initChannel(SocketChannel socketChannel) throws Exception {socketChannel.pipeline().addLast(new ServerHandler());//这里配置具体数据接收方法的处理}});ChannelFuture cf1 = sb.bind(8787).sync();//异步的绑定指定的端口ChannelFuture cf2 = sb.bind(8686).sync();//netty可以绑定多个端口cf1.channel().closeFuture().sync();//等待关闭,相当于Thread.sleep(Integer.MAX_VALUE)cf2.channel().closeFuture().sync();//关闭线程组bossGroup.shutdownGracefully();workGroup.shutdownGracefully();}
}

ServerHandler类:(用于处理server接收到的消息)

package com.zyh.study.netty.helloworld;import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;/*** @Description:* @Author: zyh* @Date: created in 2018/7/22*/
public class ServerHandler extends ChannelHandlerAdapter{/*** 重写读数据时处理的方法* @param ctx* @param msg* @throws Exception*/@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {ByteBuf buf = (ByteBuf) msg;//声明字节数组,buf.readableBytes()返回的是buf缓冲中可读的字节数byte[] req = new byte[buf.readableBytes()];//将buf缓冲区中的字节读取到字节数组req中buf.readBytes(req);String body = new String(req, "utf-8");System.out.println("Server打印接收到的信息:" + body);String response = "Server返回给Client的响应信息:" + body;//1.ctx.writeAndFlush()方法相当于连续调用了write()和flush()方法,因为write()方法只是将buf写到了渠道的缓冲区中,flush()方法会将缓冲区中的数据传给客户端//2.这里Unpooled工具类的作用就是讲字节数组转成netty的ByteBuf对象//3.这里使用了writeAndFlush()方法会自动释放buf缓冲区所以不需要想ClientHandler中那样finally中手动释放buf缓冲区了//4.addListener()方法:当监听到服务器将数据写给客户端,并且确认客户端已经收到信息后,// 服务器端就会主动去关闭跟客户端的连接,因为客户端调用了cf1.channel().closeFuture().sync()方法,所以客户端这里的阻塞就会打开,继续向后执行代码ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
//                .addListener(ChannelFutureListener.CLOSE);}/*** 重写读数据出现异常处理的方法* @param ctx* @param cause* @throws Exception*/@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {ctx.close();}
}

Client类:

package com.zyh.study.netty.helloworld;import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;/*** @Description:* @Author: zyh* @Date: created in 2018/7/22*/
public class Client {public static void main(String[] args) throws Exception{NioEventLoopGroup group = new NioEventLoopGroup();//用于处理网络通信(读写)的线程组Bootstrap b = new Bootstrap();//创建客户端辅助类工具b.group(group)//绑定线程组.channel(NioSocketChannel.class)//设置通信渠道为TCP协议.handler(new ChannelInitializer<SocketChannel>() {protected void initChannel(SocketChannel socketChannel) throws Exception {socketChannel.pipeline().addLast(new ClientHandler());//这里配置具体数据接收方法的处理}});/*与8787端口通讯*/ChannelFuture cf1 = b.connect("127.0.0.1", 8787).sync();//异步建立连接cf1.channel().write(Unpooled.copiedBuffer("hello world".getBytes()));//将“hello world”写到buf缓冲区cf1.channel().flush();//这里必须使用flush(),只用冲刷才能将buf缓冲区中的数据传给服务器端/*与8686端口通讯*/ChannelFuture cf2 = b.connect("127.0.0.1", 8686).sync();cf2.channel().writeAndFlush(Unpooled.copiedBuffer("hello netty".getBytes()));cf1.channel().closeFuture().sync();//等待关闭,相当于Thread.sleep(Integer.MAX_VALUE)cf2.channel().closeFuture().sync();group.shutdownGracefully();//关闭线程组}
}

ClientHandler类:(用于处理Client端接收到的消息)

package com.zyh.study.netty.helloworld;import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;import java.nio.ByteBuffer;/*** @Description:* @Author: zyh* @Date: created in 2018/7/22*/
public class ClientHandler extends ChannelHandlerAdapter {/*** 重写读数据时处理的方法* @param ctx* @param msg* @throws Exception*/@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {try {ByteBuf buf = (ByteBuf) msg;//声明字节数组,buf.readableBytes()返回的是buf缓冲中可读的字节数byte[] req = new byte[buf.readableBytes()];buf.readBytes(req);String body = new String(req, "utf-8");System.out.println("Client打印接收到的信息:" + body);}finally {ReferenceCountUtil.release(msg);//buf缓冲区使用完了,必须释放}}/*** 重写读数据出现异常处理的方法* @param ctx* @param cause* @throws Exception*/@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {ctx.close();}
}

netty的Helloworld---netty学习笔记相关推荐

  1. .NET 云原生架构师训练营(模块二 基础巩固 RabbitMQ HelloWorld)--学习笔记

    2.6.3 RabbitMQ -- HelloWorld 发送端 接收端 rabbitmq container 发送信息 https://www.rabbitmq.com/tutorials/tuto ...

  2. jQuery学习笔记--目录

    jQuery学习笔记--Helloworld jQuery学习笔记--DOM对象和jQuery对象 jQuery学习笔记--jQuery选择器 jQuery学习笔记--jQuery的DOM操作 jQu ...

  3. Netty学习笔记(二) 实现服务端和客户端

    在Netty学习笔记(一) 实现DISCARD服务中,我们使用Netty和Python实现了简单的丢弃DISCARD服务,这篇,我们使用Netty实现服务端和客户端交互的需求. 前置工作 开发环境 J ...

  4. Netty学习笔记(六)Pipeline的传播机制

    前面简单提到了下Pipeline的传播机制,这里再详细分析下 Pipeline的传播机制中有两个非常重要的属性inbound和outbound(AbstractChannelHandlerContex ...

  5. Netty学习笔记(二)Netty服务端流程启动分析

    先贴下在NIO和Netty里启动服务端的代码 public class NioServer { /*** 指定端口号启动服务* */public boolean startServer(int por ...

  6. Netty学习笔记(六) 简单的聊天室功能之WebSocket客户端开发实例

    在之前的Netty相关学习笔记中,学习了如何去实现聊天室的服务段,这里我们来实现聊天室的客户端,聊天室的客户端使用的是Html5和WebSocket实现,下面我们继续学习. 创建客户端 接着第五个笔记 ...

  7. Netty网络框架学习笔记-16(心跳(heartbeat)服务源码分析)

    Netty网络框架学习笔记-16(心跳(heartbeat)服务源码分析_2020.06.25) 前言: Netty 作为一个网络框架,提供了诸多功能,比如编码解码等,Netty 还提供了非常重要的一 ...

  8. Netty学习笔记:二、NIO网络应用实例-群聊系统

    实例要求: 编写一个NIO群聊系统,实现服务器端和多个客户端之间的数据简单通讯(非阻塞): 实现多人群聊: 服务器端:可以监测用户上线.离线,并实现消息转发功能: 客户端:通过channel可以无阻塞 ...

  9. Netty学习笔记 - 1 (带源码分析部分)

    2021年12月 北京 xxd 一.Netty是什么 Netty 是由 JBOSS 提供的一个 Java 开源框架,现为 Github 上的独立项目. Netty 是一个异步的.基于事件驱动的网络应用 ...

  10. Netty学习笔记二网络编程

    Netty学习笔记二 二. 网络编程 1. 阻塞模式 阻塞主要表现为: 连接时阻塞 读取数据时阻塞 缺点: 阻塞单线程在没有连接时会阻塞等待连接的到达,连接到了以后,要进行读取数据,如果没有数据,还要 ...

最新文章

  1. mysql 亿级表count_码云社 | 砺锋科技-MySQL的count(*)的优化,获取千万级数据表的总行数 - 用代码改变世界...
  2. 给力开源,.Net开源地址大收集
  3. 【NOIP2007】【Luogu1094】纪念品分组(贪心,乘船问题)
  4. 2018-2019 20165237网络对抗 Exp5 MSF基础应用
  5. 【每日提高之声明式事物】spring声明式事务 同一类内方法调用事务失效
  6. flink DataStream API使用及原理
  7. canvas手机端绘图解决方案
  8. 搭建基于云端的中间层以支持跨平台的智能视觉服务
  9. python内核死亡的原因_Python的内核由于DLL而死亡
  10. zend studio php发布_使用Zend Studio开发PHP项目
  11. python开发环境哪个好 博客园_我选用的Python开发环境
  12. 《机器学习实战》学习笔记第七章 —— AdaBoost元算法
  13. 开源GIS(五)——openlayers中interaction的select、draw与modify
  14. python能做什么excel-python处理excel总结
  15. Linux手机研发要过五大难关
  16. 私密智能搜题小助手,支持智能图片识别和智能复制,支持多接口
  17. Multisim: Inverting Amplifier Simulation
  18. 点击率 ctr 与转化率 cvr
  19. Ubuntu修改时区和更新时间
  20. 编程语言和开发环境的选择

热门文章

  1. python ttf svg path_SVG的path的使用
  2. sql 数组_sql注入中级
  3. git remote: HTTP Basic: Access denied
  4. H5禁止手机自带键盘弹出
  5. OpenCv:椭圆上点的计算方程
  6. ANN:DNN结构演进History—LSTM_NN
  7. AI制作icon标准参考线与多面板复制
  8. 拥抱开放式网络 通往下一代数据中心
  9. Jenkins安装入门
  10. 双系统,重装windows后修复linux的grub启动