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特定时间内的请…

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

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

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

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

Lua环境安装

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

蓝桥杯注意事项

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

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

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

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

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

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

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

Visual Studio安装图文详解教程

版权声明 本文原创作者&#xff1a;谷哥的小弟作者博客地址&#xff1a;http://blog.csdn.net/lfdfhl 教程说明 本教程旨在详细介绍 Visual Studio 社区版的安装过程及其注意事项。 Visual Studio简介 Visual Studio 社区版功能完备且可扩展的免费 IDE&#xff0c;可用于创…

【通俗理解】Neurosymbolic AI——融合神经网络与符号推理的智慧之力

【通俗理解】Neurosymbolic AI——融合神经网络与符号推理的智慧之力 关键词提炼 #Neurosymbolic AI #神经网络 #符号推理 #感知能力 #逻辑能力 #认知水平 #智慧与力量 第一节&#xff1a;Neurosymbolic AI的类比与核心概念 Neurosymbolic AI就像是给神经网络这位“大力士”…

神策数据客户旅程 GPT:以 AI 驱动客户旅程及埋点落地

数据驱动时代&#xff0c;随着 AI 在数据处理及分析方面的能力日渐强大&#xff0c;将二者结合&#xff0c;可以帮助企业效能提升&#xff0c;获取更多商业价值。 我们在 AI 大模型探索过程中发现&#xff0c;产品经理、技术人员、市场营销人员以及需要数据驱动决策的团队&…

基于opencv的人脸闭眼识别疲劳监测

1. 项目简介 本项目旨在实现基于眼部特征的眨眼检测&#xff0c;通过监测眼睛开闭状态来计算眨眼次数&#xff0c;从而应用于疲劳监测、注意力检测等场景。使用了面部特征点检测算法&#xff0c;以及眼部特征比率&#xff08;EAR, Eye Aspect Ratio&#xff09;来判断眼睛的闭…

可观测日北京|观测云:可观测性需要做到“三个一”

2024年10月&#xff0c;备受期待的中国可观测日「北京站」圆满落幕。本次活动汇聚了来自云计算、技术创新等领域的专家&#xff0c;探讨了探讨了可观测性在云计算和数字化转型中扮演的角色。观测云也在活动展示了作为可观测性行业领袖的技术力和创新力。 观测云技术亮点&#…

python画图|坐标轴显隐设置

【1】引言 前序学习中&#xff0c;已经发现坐标轴的显示具有至关重要的影响&#xff0c;因此今天继续探索相关技巧&#xff1a;坐标轴显隐设置。 前序学习内容可通过下述链接直达&#xff1a; python画图| 对齐图名和标签-CSDN博客 【2】官网教程 点击下方链接可以直达官网…

react 基础学习笔记

1.react 语法 ①数据渲染 函数组件将HTML结构直接写在函数的返回值中 JSX只能有一个根元素 JSX插值写法 插值可以使用的位置 1.标签内容&#xff1b; 2.标签属性 JSX 条件渲染&#xff1a;三目运算符&#xff1b; JSX根据数据进行列表渲染&#xff1a;map()方法&#x…