Netty简单应用

1.服务端构建

  • 接收客户端请求,打印请求消息;
  • 消息采用内置String作为编码与解码器;
  • 开启信息输入监听线程,发送消息至客户端;

1.1 服务端消息处理类

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;import java.util.ArrayList;
import java.util.List;/*** @author : luobei* @date : 2024/10/23 11:16* @Description : 处理类:处理channel接收到的消息*/
public class NettyServerHandler extends ChannelInboundHandlerAdapter {public static List<Channel> channelList = new ArrayList<Channel>();@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {super.channelActive(ctx);channelList.add(ctx.channel());}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {System.out.println("服务端收到消息:"+msg);}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {System.out.println("服务端读取数据异常:");cause.printStackTrace();ctx.close();}
}

1.2 服务端启动类

import io.netty.bootstrap.ServerBootstrap;
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.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;/*** @author : luobei* @date : 2024/10/23 11:03*/
public class NettyServerProvider {private int port;public NettyServerProvider(int port){this.port = port;}//netty服务端启动public void start() throws InterruptedException {//用来接收进来的连接EventLoopGroup bossGroup = new NioEventLoopGroup();//用来处理已经被接收的连接,bossGroup接收到连接就会把连接信息注册到workerGroup上EventLoopGroup workerGroup = new NioEventLoopGroup();try {//nio服务的启动类ServerBootstrap bootstrap = new ServerBootstrap();//配置nio服务参数bootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class) //说明一个新的Channel.option(ChannelOption.SO_BACKLOG,128) //设置Tcp最大缓存连接个数.childOption(ChannelOption.SO_KEEPALIVE,true) //设置保持连接.handler(new LoggingHandler(LogLevel.INFO)) //设置打印日志级别.childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel socket) throws Exception {//管道注册handlerChannelPipeline pipeline = socket.pipeline();//编码通道处理pipeline.addLast("decode",new StringDecoder());//转码通道处理pipeline.addLast("encode",new StringEncoder());//处理接收到的请求pipeline.addLast(new NettyServerHandler());}});System.out.println("--------------服务端启动--------------");//监听输入框消息并发送给所有客户端new Thread(new Runnable() {@Overridepublic void run() {try {while (true){BufferedReader in = new BufferedReader(new InputStreamReader(System.in));String msg = null;msg = in.readLine();if (NettyServerHandler.channelList.size()>0){for (Channel channel : NettyServerHandler.channelList) {channel.writeAndFlush(msg);}}}} catch (IOException e) {throw new RuntimeException(e);}}}).start();//绑定端口,开始接收连接ChannelFuture channelFuture = null;channelFuture = bootstrap.bind(port).sync();channelFuture.channel().closeFuture().sync();} finally {bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}public static void main(String[] args) throws InterruptedException {new NettyServerProvider(8888).start();}}

2.客户端构建

  • 发起请求,与服务端建立连接;
  • 监听服务端下发消息,并将信息打印出来;
  • 开启信息输入监听线程,将消息发送值服务端;

2.1 客户端消息处理类

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;/*** @author : luobei* @date : 2024/10/23 13:15*/
public class NettyClientHandler extends ChannelInboundHandlerAdapter {public static Channel serverChannel = null;@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {super.channelActive(ctx);serverChannel = ctx.channel();}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {System.out.println("客户端收到消息:"+msg);}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {System.out.println("客户端读取数据异常:");cause.printStackTrace();ctx.close();}
}

2.2 客户端启动类

import io.netty.bootstrap.Bootstrap;
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.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;/*** @author : luobei* @date : 2024/10/23 13:20*/
public class NettyClientServer {//要请求的IP地址private String ip;//服务器端口private int port;public NettyClientServer(String ip, int port){this.ip = ip;this.port = port;}//启动服务private void start() throws InterruptedException {EventLoopGroup bossGroup = new NioEventLoopGroup();Bootstrap bootstrap = new Bootstrap();bootstrap.group(bossGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE,true).handler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel socketChannel) throws Exception {ChannelPipeline pipeline = socketChannel.pipeline();pipeline.addLast("decode",new StringDecoder());pipeline.addLast("encode",new StringEncoder());socketChannel.pipeline().addLast(new NettyClientHandler());}});System.out.println("-----------客户端启动-----------");ChannelFuture future = bootstrap.connect(ip,port).sync();String msg = "客户端发起连接请求";Channel channel = future.channel();channel.writeAndFlush(msg);new Thread(new Runnable() {@Overridepublic void run() {try {while (true){BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));String msg = reader.readLine();channel.writeAndFlush(msg);}} catch (Exception e) {e.printStackTrace();}}}).start();}public static void main(String[] args) throws InterruptedException {new NettyClientServer("127.0.0.1",8888).start();}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/57457.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

双十一好物必买清单攻略,这几款双十一必入的宝藏好物分享

随着双十一购物节的脚步日益临近&#xff0c;无数消费者都在期待着在这个年度大促中抢购到自己心仪已久的好物&#xff0c;为了帮助大家更好地规划购物计划&#xff0c;精选出真正值得入手的宝藏产品&#xff0c;我们特别整理了这份双十一好物必买清单攻略&#xff0c;无论你是…

spring day1023

ok了家人们&#xff0c;今天继续学习spring框架&#xff0c; 七.Spring的注解开发 在开发中&#xff0c;配置文件中 Bean 标签会非常多&#xff0c;难以维护。怎么 办&#xff1f; 使用注解的形式替代 xml 配置&#xff0c;可以将一些繁杂的 spring 配置 从工程中消除掉&…

业余时间试一试利用AI 人工智能赚钱

内容创作与写作&#xff1a; 撰写文章&#xff1a;许多网站、博客和企业都需要大量的优质内容。利用 AI 工具如 ChatGPT 等&#xff0c;获取文章的思路、框架甚至初稿&#xff0c;然后根据自己的知识和经验进行修改、润色和完善。你可以在一些自由撰稿人平台、内容创作平台上承…

智能园艺:Spring Boot植物健康系统

1系统概述 1.1 研究背景 随着计算机技术的发展以及计算机网络的逐渐普及&#xff0c;互联网成为人们查找信息的重要场所&#xff0c;二十一世纪是信息的时代&#xff0c;所以信息的管理显得特别重要。因此&#xff0c;使用计算机来管理植物健康系统的相关信息成为必然。开发合适…

es索引库操作和使用RestHignLevelClient客户端操作es

目录 es索引库操作 mapping映射操作 索引库的CURD操作 1.创建索引库和映射 ​编辑 2.查询索引库 3.删除索引库 4.修改索引库 5.总结 文档的CURD操作 1.新增文档 2.查询文档 3.删除文档 4.修改文档 全量修改 增量修改 5.总结 RestAPI 使用API例子 需要的数…

一文掌握异步web框架FastAPI(五)-- 中间件(测试环境、访问速率限制、请求体解析、自定义认证、重试机制、请求频率统计、路径重写)

接上篇:一文掌握异步web框架FastAPI(四)-CSDN博客 目录 七、中间件 15、测试环境中间件 16、访问速率限制中间件,即限制每个IP特定时间内的请求数(基于内存,生产上要使用数据库) 1)限制单ip访问速率 2)增加限制单ip并发(跟上面的一样,也是限制每个IP特定时间内的请…

代码随想录算法训练营第二十四天|Day24 回溯算法

93.复原IP地址 题目链接/文章讲解&#xff1a;https://programmercarl.com/0093.%E5%A4%8D%E5%8E%9FIP%E5%9C%B0%E5%9D%80.html 视频讲解&#xff1a;https://www.bilibili.com/video/BV1XP4y1U73i/ 思路 char** result; int resultTop; int segments[3]; int isValid(char* s…

大模型算法二次开发,基本思路详细拆解

[ 导读 随着众多大模型相继问世&#xff0c;大模型二次开发、大模型微调成为一项热门技术。本文为大家总结了大模型二次开发的基本方法与思路&#xff0c;希望对大家有所帮助。 开发方法分类 1、领域知识注入&#xff1a;Continue PreTraining(增量预训练),一般垂直大模型是…

【drone】drone 整合 gitea | ubuntu 通过docker-compose方式部署drone的全流程 整合gitea

一、前期准备 1、ubuntu环境 确定是否具有 ssh: service ssh start,如果没有,使用:apt install openssh-server 进行安装查看 Linux 的 IP 地址: ifconfig,命令不可用时,通过:apt install net-tools安装命令可选:设置 root 的密码: sudo passwd root可选:开启 root…

使用Python读取word表格里的数据,存为excel表格,以此来解决word表格复制到excel表格一个单元格变过个单元格的问题

一、前言 最近同事遇到一个棘手的事情&#xff0c;要把有1000多行的word表格&#xff0c;转成excel表格&#xff0c;采取直接复制的方式&#xff0c;word里面表格的内容有很多的回车&#xff0c;导致表格复制到excel后&#xff0c;word里一个单元格在excel里变成了多个单元格。…

(STM32笔记)十二、DMA的基础知识与用法

我用的是正点的STM32F103来进行学习&#xff0c;板子和教程是野火的指南者。 之后的这个系列笔记开头未标明的话&#xff0c;用的也是这个板子和教程。 DMA的基础知识与用法 一、DMA功能框图1、DMA请求2、通道3、仲裁器 二、DMA传输设置1、数据来源与数据去向外设到存储器存储器…

如何在verilog设计的磁盘阵列控制器中实现不同RAID级别(如RAID 0、RAID 1等)的切换?

以下是一种在Verilog设计的磁盘阵列控制器中实现不同RAID级别(以RAID 0和RAID 1为例)切换的方法: 添加控制信号 在磁盘阵列控制器模块中添加一个输入信号,例如raid_mode,用于选择RAID模式。假设raid_mode = 0表示RAID 0模式,raid_mode = 1表示RAID 1模式。module raid_co…

前端算法:堆

目录 一、堆 1.堆是什么&#xff1f; 2.堆的性质 3.堆的实现 4.基本操作 5.时间复杂度 二、代码实现 1.最大堆实现 2.最小堆实现 一、堆 1.堆是什么&#xff1f; 堆能用树来表示&#xff0c;并且一般树的实现都是通过链表&#xff0c;而二叉堆是一种特殊的堆&#xf…

GO基础(string相关)

本博文包含了18个小内容&#xff0c;有判断字符串是否以另一个字符串开头、字符串包含关系判断、4、判断非ASCII编码字符、字符串替换、统计字符串出现的次数、重复字符串、修改字符串大写、修改字符串小写、剔除字符串开头和结尾的空白符号、剔除指定字符、剔除开头字符串、剔…

Lua环境安装

软考鸭微信小程序 学软考,来软考鸭! 提供软考免费软考讲解视频、题库、软考试题、软考模考、软考查分、软考咨询等服务 Lua是一种轻量级、小巧且易于嵌入应用程序的脚本语言&#xff0c;广泛用于游戏开发、Web开发、自动化脚本等领域。本文将详细介绍如何在不同操作系统上安装L…

蓝桥杯注意事项

蓝桥杯注意事项 比赛注意事项 能暴力枚举就暴力枚举&#xff0c;能用简单的思路做就尽量用简单的思路做。认真审核题目的题意和输入输出的要求&#xff0c;避免因为误解题意而导致题目错误。对于提供多组测试样例或者需要对一个过程重复进行循环的代码&#xff0c;要时刻记住…

六大设计原则之一——单一职责原则

单一职责原则 面向对象三大特性之一的 封装 指的就是将单一事物抽象出来组合成一个类&#xff0c;所以我们在设计类的时候每个类中处理的是单一事物而不是某些事物的集合。 设计模式中所谓的 单一职责原则(Single Responsibility Principle - SRP)&#xff0c;就是对一个类而…

【硬啃Dash-Fastapi-Admin】03-requirements-pg.txt 速览

文章目录 dash2.18.1 纯Python的Web应用框架Python Dash库的功能介绍和用法示例功能介绍用法示例 Flask-Compress1.15 Flask响应数据的压缩功能介绍用法示例注意事项 feffery-antd-charts0.1.0rc5 数据可视化组件库功能介绍用法示例 feffery-antd-components0.3.8 Dash 第三方组…

autMan奥特曼机器人-实时翻译的用法

一、基本配置 访问并登录百度翻译开放平台&#xff1a;https://api.fanyi.baidu.com/ 进入开发者信息获取 APP ID和密钥&#xff0c;并开通“通用文本翻译”服务 autMan应用市场->我的->找到“实时翻译”插件安装后去点击“配参” 二、使用示例 假如你和一个俄国人聊…

C程序设计语言精髓 单向链表

目录 单向链表---定义 单向链表---建立 单向链表---删除 单向链表---插入​ 单向链表---输出​ 单向链表---定义 单向链表---建立 单向链表---删除 单向链表---插入 单向链表---输出