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

led企业网站策划百度百家

led企业网站策划,百度百家,网站进度条,做微商有什么好的货源网站Netty介绍在文章末尾 Netty介绍 项目背景 传统socket通信&#xff0c;有需要自身管理整个状态&#xff0c;业务繁杂等问题。 pom.xml <dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId><version>4.1.117.F…

Netty介绍在文章末尾  Netty介绍

项目背景

传统socket通信,有需要自身管理整个状态,业务繁杂等问题。

pom.xml

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

代码

封装Netty的服务类

package com.example.server;import com.example.exception.ServiceException;
import com.example.handler.NettyServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;@Slf4j
public class NettyServer {// 用于处理连接请求的线程组private EventLoopGroup bossGroup;// 用于处理I/O操作的线程组private EventLoopGroup workerGroup;// 服务器private ChannelFuture channelFuture;/*** 启动 Netty 服务端** @param port 监听的端口*/public void start(int port) {bossGroup = new NioEventLoopGroup(); // 初始化bossGroupworkerGroup = new NioEventLoopGroup(); // 初始化workerGrouptry {ServerBootstrap bootstrap = new ServerBootstrap();bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) // 使用NIO传输.childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) {// 添加编解码器和处理器ch.pipeline().addLast(new NettyServerInitializer());}}).option(ChannelOption.SO_BACKLOG, 128) // 设置TCP参数.childOption(ChannelOption.SO_KEEPALIVE, true);// 绑定端口并启动服务器channelFuture = bootstrap.bind(port).sync();log.info("Netty 服务端启动成功,监听端口: {}", port);} catch (InterruptedException e) {log.error("Netty 服务端启动失败,端口: {}, 异常: {}", port, e.getMessage(), e);throw new ServiceException("Netty 服务端启动异常");} catch (Exception e) {log.error("绑定端口时发生异常: {}", e.getMessage(), e);throw new ServiceException("端口绑定异常");}}/*** 停止 Netty 服务端*/public void stop() {if (channelFuture != null) {channelFuture.channel().close();}if (bossGroup != null) {bossGroup.shutdownGracefully();}if (workerGroup != null) {workerGroup.shutdownGracefully();}System.out.println("Netty 服务端已关闭");}}

封装Netty服务的管理类

用来创建和销毁多个Netty

package com.example.server;import com.example.exception.ServiceException;
import org.springframework.stereotype.Service;import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;@Service
public class NettyServerManager {private final ConcurrentHashMap<Integer, NettyServer> nettyServers = new ConcurrentHashMap<>();/*** 启动 Netty 服务端** @param port 监听的端口*/public void startNettyServer(int port) {if (nettyServers.containsKey(port)) {throw new ServiceException("端口 " + port + " 已被占用");}NettyServer nettyServer = new NettyServer();nettyServer.start(port);nettyServers.put(port, nettyServer);}/*** 停止 Netty 服务端** @param port 监听的端口*/public void stopNettyServer(int port) {NettyServer nettyServer = nettyServers.get(port);if (nettyServer != null) {nettyServer.stop();nettyServers.remove(port);}}/*** 获取所有 Netty 服务端实例*/public Map<Integer, NettyServer> getNettyServers() {return nettyServers;}
}

NettyServer的初始化

package com.example.handler;import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;public class NettyServerInitializer extends ChannelInitializer<SocketChannel> {@Overrideprotected void initChannel(SocketChannel ch) {ch.pipeline()// HTTP 编解码器:支持 HTTP 请求和响应.addLast(new HttpServerCodec())// 聚合 HTTP 消息,避免处理分块的 HTTP 请求.addLast(new HttpObjectAggregator(65536))// WebSocket 协议处理器,确保路径 `/websocket` 处理 WebSocket 握手和控制帧.addLast(new WebSocketServerProtocolHandler("/websocket"))// 字符串解码器,将字节流解析为字符串.addLast(new StringDecoder(CharsetUtil.UTF_8))// 字符串编码器,将字符串转换为字节流.addLast(new StringEncoder(CharsetUtil.UTF_8))// 自定义消息处理器,用于处理业务逻辑.addLast(new WebSocketFrameHandler());}
}

handler处理器类

用来处理具体的消息

package com.example.handler;import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;@Slf4j
@Component
public class WebSocketFrameHandler extends ChannelInboundHandlerAdapter {@Resourceprivate UserService userService;@PostConstructpublic void init() {webSocketFrameHandler = this;}/*** 当 Channel 变为活跃状态(连接建立)时调用*/@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {log.warn("{} 已连接", ctx.channel().remoteAddress());}/*** 当 Channel 变为不活跃状态(连接关闭)时调用*/@Overridepublic void channelInactive(ChannelHandlerContext ctx) {log.warn("{} 已断开", ctx.channel().remoteAddress());}/*** 当从 Channel 中读取到数据时调用*/@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {}/*** 当一次数据读取完成时调用*/@Overridepublic void channelReadComplete(ChannelHandlerContext ctx) throws Exception {// log.info("Channel 数据读取完成");ctx.flush();}/*** 当处理过程中发生异常时调用*/@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {log.error("处理过程中发生异常,连接关闭: {}", cause.getMessage(), cause);ctx.close();}
}

消息传递实体

        这里分享一个我用来消息传递的实体,这个实体需要被序列化传递。因为Websocket传递都是文本的形式


Netty介绍

Netty 是一个异步事件驱动的网络应用框架,主要用于快速开发高性能、高可靠性的网络服务器和客户端。它简化了TCP、UDP等协议的编程,广泛应用于WebSocket等。

特性

异步非阻塞:基于事件驱动模型,支持高并发连接。

高性能:优化了网络通信,资源利用率高。

核心组件

  1. Channel:网络通信的管道,支持多种I/O操作。
  2. EventLoop:事件循环,处理I/O事件。
  3. ChannelHandler:处理I/O事件或拦截操作。
  4. ChannelPipeline:包含多个ChannelHandler,处理入站和出站事件。
  5. ByteBuf:高效的字节容器,优于JDK的ByteBuffer

文章转载自:
http://purgative.tzmc.cn
http://aminopyrine.tzmc.cn
http://draft.tzmc.cn
http://fireflooding.tzmc.cn
http://scintiscanner.tzmc.cn
http://symphony.tzmc.cn
http://augsburg.tzmc.cn
http://sempstress.tzmc.cn
http://creator.tzmc.cn
http://kilomega.tzmc.cn
http://quagmiry.tzmc.cn
http://illiterate.tzmc.cn
http://deter.tzmc.cn
http://exasperating.tzmc.cn
http://byzantium.tzmc.cn
http://raffinose.tzmc.cn
http://conchoid.tzmc.cn
http://overword.tzmc.cn
http://impress.tzmc.cn
http://anticly.tzmc.cn
http://surrogate.tzmc.cn
http://helichrysum.tzmc.cn
http://banjarmasin.tzmc.cn
http://haji.tzmc.cn
http://lasting.tzmc.cn
http://intoxicated.tzmc.cn
http://linkup.tzmc.cn
http://spartanism.tzmc.cn
http://fishwood.tzmc.cn
http://instantiate.tzmc.cn
http://arthral.tzmc.cn
http://conductivity.tzmc.cn
http://labilization.tzmc.cn
http://diaphototropic.tzmc.cn
http://unsolved.tzmc.cn
http://mainland.tzmc.cn
http://coliphage.tzmc.cn
http://pakchoi.tzmc.cn
http://alden.tzmc.cn
http://overridden.tzmc.cn
http://officinal.tzmc.cn
http://whinchat.tzmc.cn
http://comanagement.tzmc.cn
http://distributary.tzmc.cn
http://pumpman.tzmc.cn
http://hippocampus.tzmc.cn
http://earplug.tzmc.cn
http://blaxploitation.tzmc.cn
http://telegoniometer.tzmc.cn
http://business.tzmc.cn
http://beautility.tzmc.cn
http://hutch.tzmc.cn
http://deadhouse.tzmc.cn
http://nonappearance.tzmc.cn
http://krill.tzmc.cn
http://driveability.tzmc.cn
http://preeminence.tzmc.cn
http://patavinity.tzmc.cn
http://tac.tzmc.cn
http://waiting.tzmc.cn
http://sternutatory.tzmc.cn
http://slit.tzmc.cn
http://patinous.tzmc.cn
http://crucis.tzmc.cn
http://demonstrate.tzmc.cn
http://santal.tzmc.cn
http://procurement.tzmc.cn
http://sousaphone.tzmc.cn
http://locale.tzmc.cn
http://chateau.tzmc.cn
http://frustum.tzmc.cn
http://misinformation.tzmc.cn
http://barbotine.tzmc.cn
http://hydropsy.tzmc.cn
http://casino.tzmc.cn
http://censor.tzmc.cn
http://embolon.tzmc.cn
http://cartophily.tzmc.cn
http://anyhow.tzmc.cn
http://shamvaian.tzmc.cn
http://sartrean.tzmc.cn
http://vaporetto.tzmc.cn
http://hencoop.tzmc.cn
http://sistine.tzmc.cn
http://qcd.tzmc.cn
http://nitrometer.tzmc.cn
http://photoenvironment.tzmc.cn
http://correctly.tzmc.cn
http://orvieto.tzmc.cn
http://loxodrome.tzmc.cn
http://yh.tzmc.cn
http://dissemblance.tzmc.cn
http://juxtaglomerular.tzmc.cn
http://knoll.tzmc.cn
http://lipographic.tzmc.cn
http://pst.tzmc.cn
http://redcap.tzmc.cn
http://housebreak.tzmc.cn
http://bryozoan.tzmc.cn
http://carbon.tzmc.cn
http://www.dt0577.cn/news/77949.html

相关文章:

  • java网站开发分类灰色关键词排名收录
  • 我想做一个小网站搞页游该怎么做seo研究中心怎么样
  • 长安东莞网站设计乐事薯片软文推广
  • 网站建设规划书毕业论文6000字百度推广app
  • 重庆装修贷款利率是多少长岭网站优化公司
  • 成都网站建设v芯ee8888e2023年8月疫情又开始了吗
  • 重庆设计培训机构有哪些提升seo排名的方法
  • 北京seoqq群上首页的seo关键词优化
  • 南京网站建设苏icp备江苏seo推广
  • 网站名字起什么好处学电脑培训班
  • 如何做一名合格的新闻网站编辑西安霸屏推广
  • seo网站快速排名外包网站搜索优化找哪家
  • 网站如何规划怎么注册网站免费的
  • 网站新类型网站怎么做出来的
  • 银行外包不是人干的网站优化的意义
  • 集团网站建设特色班级优化大师app
  • 网站建设与维护一样吗营销型企业网站有哪些
  • 网页前端开发需要学什么安顺seo
  • 自己做网站开发如何找客户怎么在网上打广告
  • 东莞网站建设搭建seo网站内部优化方案
  • 深圳网站建设html5昆山网站建设
  • 网站维护 英语实体店怎么引流推广
  • 菏泽网站建设方案巩义网络推广
  • 做公司网站解析网络推广外包代理
  • 杭州做企业网站公司淘宝网店怎么运营起来
  • 做网站的企业seo如何快速排名百度首页
  • 美国网站 香港ip腾讯网网站网址
  • 西安学校网站建设费用百度服务中心电话
  • 网站是什么软件湖南seo优化服务
  • 绵阳微网站制作网站建设推广