当前位置: 首页 > news >正文

netty实现简单的客户端、服务端互相发消息

引入maven依赖

<dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId><version>4.1.20.Final</version>
</dependency>

一、服务端

1、创建服务端启动类

public class MyServer {public static void main(String[] args) throws Exception {//创建两个线程组 boosGroup、workerGroupEventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();try {//创建服务端的启动对象,设置参数ServerBootstrap bootstrap = new ServerBootstrap();//设置两个线程组boosGroup和workerGroupbootstrap.group(bossGroup, workerGroup)//设置服务端通道实现类型    .channel(NioServerSocketChannel.class)//设置线程队列得到连接个数    .option(ChannelOption.SO_BACKLOG, 128)//设置保持活动连接状态    .childOption(ChannelOption.SO_KEEPALIVE, true)//使用匿名内部类的形式初始化通道对象    .childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel socketChannel) throws Exception {//给pipeline管道设置处理器socketChannel.pipeline().addLast(new MyServerHandler());}});//给workerGroup的EventLoop对应的管道设置处理器System.out.println("服务端已经准备就绪...");//绑定端口号,启动服务端ChannelFuture channelFuture = bootstrap.bind(6666).sync();//对关闭通道进行监听channelFuture.channel().closeFuture().sync();} finally {bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}
}

2、创建服务端处理器

/*** 自定义的Handler需要继承Netty规定好的HandlerAdapter* 才能被Netty框架所关联,有点类似SpringMVC的适配器模式**/
public class MyServerHandler extends ChannelInboundHandlerAdapter {@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {//获取客户端发送过来的消息ByteBuf byteBuf = (ByteBuf) msg;System.out.println("收到客户端" + ctx.channel().remoteAddress() + "发送的消息:" + byteBuf.toString(CharsetUtil.UTF_8));}@Overridepublic void channelReadComplete(ChannelHandlerContext ctx) throws Exception {//发送消息给客户端ctx.writeAndFlush(Unpooled.copiedBuffer("服务端已收到消息", CharsetUtil.UTF_8));}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {//发生异常,关闭通道ctx.close();}
}

二、客户端

1、创建客户端启动类

public class MyClient {public static void main(String[] args) throws Exception {NioEventLoopGroup eventExecutors = new NioEventLoopGroup();try {//创建bootstrap对象,配置参数Bootstrap bootstrap = new Bootstrap();//设置线程组bootstrap.group(eventExecutors)//设置客户端的通道实现类型    .channel(NioSocketChannel.class)//使用匿名内部类初始化通道.handler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {//添加客户端通道的处理器ch.pipeline().addLast(new MyClientHandler());}});System.out.println("客户端准备就绪...");//连接服务端ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6666).sync();//对通道关闭进行监听channelFuture.channel().closeFuture().sync();} finally {//关闭线程组eventExecutors.shutdownGracefully();}}
}

2、创建客户端处理器

public class MyClientHandler extends ChannelInboundHandlerAdapter {@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {//发送消息到服务端ctx.writeAndFlush(Unpooled.copiedBuffer("Are you good?", CharsetUtil.UTF_8));}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {//接收服务端发送过来的消息ByteBuf byteBuf = (ByteBuf) msg;System.out.println("收到服务端" + ctx.channel().remoteAddress() + "的消息:" + byteBuf.toString(CharsetUtil.UTF_8));}
}

http://www.lryc.cn/news/294424.html

相关文章:

  • 利用jmeter完成简单的压力测试
  • 【手写数据库toadb】toadb物理存储模型,数据库物理存储原理,物理文件组织关系以及行列混合模型存储结构
  • MySQL-----DDL基础操作
  • 【MySQL】在 Centos7 环境安装 MySQL -- 详细完整教程
  • 理解React中的setState()方法
  • 数据库管理-第144期 深入使用EMCC-01(20240204)
  • flask_django_python五金电商网络营销的可视化分析研究
  • Java并发(二十三)----同步模式之保护性暂停
  • ###C语言程序设计-----C语言学习(9)#函数基础
  • Dockerfile文件参数配置和使用
  • Java实现婚恋交友网站 JAVA+Vue+SpringBoot+MySQL
  • React16源码: React中详解在渲染阶段Suspend的源码实现
  • mac电脑风扇控制软件:Macs Fan Control Pro for mac 激活版
  • easyexcel解析跨多行的数据
  • 双目相机立体匹配基础
  • 【图论】网络流
  • 【Matplotlib】figure方法 你真的会了吗!?
  • [C++]继承(续)
  • 恒创科技:服务器内存不足影响大吗?
  • 深入理解网络通信和TCP/IP协议
  • Open CASCADE学习|分割曲线
  • vulhub中Adminer远程文件读取漏洞复现(CVE-2021-43008)
  • MOS管驱动电流估算-Qg参数
  • Vision Transfomer系列第一节---从0到1的源码实现
  • 【CSS + ElementUI】更改 el-carousel 指示器样式且隐藏左右箭头
  • Ubuntu 22.04 上安装和使用 Go
  • ES6-const
  • Android消息通知Notification
  • 2V2无人机红蓝对抗仿真
  • VUE3语法--computed计算属性中get和set使用案例