Netty(九) Netty会话清除

2024-06-20 08:58
文章标签 netty 会话 清除

本文主要是介绍Netty(九) Netty会话清除,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Netty(九) Netty会话清除

netty学习目录
一、Netty(一) NIO例子
二、Netty(二) netty服务端
三、Netty(三) Netty客户端+服务端
四、Netty(四) 简化版Netty源码
五、Netty(五)Netty5.x服务端
六、Netty(六) Netty Http 服务器例子
七、Netty(七) Netty服务端+客户端代码
八、Netty(八) Netty多客户端连接例子
九、Netty(九) Netty会话清除
十、Netty(十) Netty自定义编码器解码器
十一、Netty(十一) Netty对象传输

package com.zqw.netty5x.heart;import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
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.timeout.IdleStateHandler;public class Server {public static void main(String[] args) {ServerBootstrap bootstrap = new ServerBootstrap();EventLoopGroup boss = new NioEventLoopGroup();EventLoopGroup worker = new NioEventLoopGroup();try{bootstrap.group(boss, worker);bootstrap.channel(NioServerSocketChannel.class);bootstrap.childHandler(new ChannelInitializer<Channel>() {@Overrideprotected void initChannel(Channel ch) throws Exception {ch.pipeline().addLast(new StringEncoder());ch.pipeline().addLast(new StringDecoder());ch.pipeline().addLast(new IdleStateHandler(5,5,10));ch.pipeline().addLast(new ServerHandler());}});bootstrap.option(ChannelOption.SO_BACKLOG,1024);bootstrap.childOption(ChannelOption.TCP_NODELAY, true);bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);ChannelFuture future = bootstrap.bind(7777);System.out.println("服务启动!");future.channel().closeFuture().sync();}catch (Exception e){e.printStackTrace();}finally {boss.shutdownGracefully();worker.shutdownGracefully();}}
}
package com.zqw.netty5x.heart;import io.netty.channel.*;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.concurrent.EventExecutorGroup;public class ServerHandler extends SimpleChannelInboundHandler<String> {@Overrideprotected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {System.out.println(msg);ctx.writeAndFlush("回话");}@Overridepublic void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {if(evt instanceof IdleStateEvent){IdleStateEvent event = (IdleStateEvent) evt;if(event.state() == IdleState.ALL_IDLE){ChannelFuture future = ctx.writeAndFlush("我要把你清除掉了");future.addListener(new ChannelFutureListener() {@Overridepublic void operationComplete(ChannelFuture future) throws Exception {future.channel().close();}});return;}}super.userEventTriggered(ctx, evt);}
}
package com.zqw.netty5x.heart;import com.zqw.netty5x.ClientHandler1;
import com.zqw.netty5x.MutiClient1;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;public class MultiClient {private Bootstrap bootstrap = new Bootstrap();private List<Channel> channels = new ArrayList<>();private AtomicInteger integer = new AtomicInteger();public void init(int count){EventLoopGroup worker = new NioEventLoopGroup();bootstrap.group(worker);bootstrap.channel(NioSocketChannel.class);bootstrap.handler(new ChannelInitializer<io.netty.channel.Channel>() {@Overrideprotected void initChannel(io.netty.channel.Channel ch) throws Exception {ch.pipeline().addLast(new StringEncoder());ch.pipeline().addLast(new StringDecoder());ch.pipeline().addLast(new ClientHandler1());}});for (int i = 0; i < count ; i++) {ChannelFuture future = bootstrap.connect("192.168.1.4",7777);channels.add(future.channel());}}public Channel next(){return getChannel(0);}private Channel getChannel(int count) {Channel channel = channels.get(Math.abs(integer.getAndIncrement() % channels.size()));if(!channel.isActive()){if(count >= channels.size()){throw new RuntimeException("没有可用的channel");}reconnect(channel);return getChannel(++count);}return channel;}private void reconnect(Channel channel) {synchronized (channel){System.out.println("重连。。。。。");int index = channels.indexOf(channel);channel = bootstrap.connect("192.168.1.4",7777).channel();channels.set(index, channel);}}public static void main(String[] args) {MultiClient mutiClient = new MultiClient();mutiClient.init(10);Scanner scanner = new Scanner(System.in);while(true){System.out.println("请输入:");String str = scanner.next();try{Channel channel = mutiClient.next();channel.writeAndFlush(str);}catch (Exception e){e.printStackTrace();}}}
}
package com.zqw.netty5x;import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelHandlerInvoker;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.EventExecutorGroup;public class ClientHandler1 extends SimpleChannelInboundHandler<String> {@Overrideprotected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {System.out.println(msg);}
}

这篇关于Netty(九) Netty会话清除的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1077682

相关文章

SpringBoot集成Netty,Handler中@Autowired注解为空

最近建了个技术交流群,然后好多小伙伴都问关于Netty的问题,尤其今天的问题最特殊,功能大概是要在Netty接收消息时把数据写入数据库,那个小伙伴用的是 Spring Boot + MyBatis + Netty,所以就碰到了Handler中@Autowired注解为空的问题 参考了一些大神的博文,Spring Boot非controller使用@Autowired注解注入为null的问题,得到

Netty ByteBuf 释放详解:内存管理与最佳实践

Netty ByteBuf 释放详解:内存管理与最佳实践 在Netty中(学习netty请参考:🔗深入浅出Netty:高性能网络应用框架的原理与实践),管理ByteBuf的内存是至关重要的(学习ByteBuf请参考:🔗Netty ByteBuf 详解:高性能数据缓冲区的全面介绍)。未能正确释放ByteBuf可能会导致内存泄漏,进而影响应用的性能和稳定性。本文将详细介绍如何正确地释放ByteB

netty中常用概念的理解

目录   目录ChannelHandler ChannelHandler功能介绍通过ChannelHandlerAdapter自定义拦截器ChannelHandlerContext接口ChannelPipeline ChannelPipeline介绍ChannelPipeline工作原理ChannelHandler的执行顺序   在《Netty权威指南》(第二版)中,ChannelP

[Spring Boot]Netty-UDP客户端

文章目录 简述Netty-UDP集成pom引入ClientHandler调用 消息发送与接收在线UDP服务系统调用 简述 最近在一些场景中需要使用UDP客户端进行,所以开始集成新的东西。本文集成了一个基于netty的SpringBoot的简单的应用场景。 Netty-UDP集成 pom引入 <!-- netty --><dependency><group

Netty的HTTP协议开发

Netty的HTTP协议开发        由于netty天生是异步事件驱动的架构,因此基于NIO TCP协议栈开发的HTTP协议栈也是异步非阻塞的。   Netty的HTTP协议栈无论在性能还是可靠性上,都表现优异,非常适合在非web容器的场景下应用,相比于传统的tomcat,jetty等web容器,它更轻量和小巧。 一.HTTP服务端开发 1.1 HttpFileServer实现 p

Netty之Jboss Marshalling编解码

Netty之JbossMarshalling编解码     JbossMarshalling是一个java对象序列化包,对JDK默认的序列化框架进行了优化,但又保持跟java.io.Serializable接口的兼容,同时增加了一些可调的参数和附加的特性,这些参数和特性可通过工厂类进行配置。 一.服务端开发 1.1 SubReqServer实现 package marshalling;

Netty的java序列化实现

Netty的java序列化实现 一.java序列化开发 1.1 服务端的开发 1.1.1 使用netty对POJO对象进行序列化 package serializable;   import java.io.Serializable; /*  * 对POJO对象进行序列化 ,订购请求POJO  */ public class SubscribeReq implementsSer

Netty中分隔符和定长解码器的应用

一.使用DelimiterBasedFrameDecoder自动完成以分隔符作为结束标志的解码 1.1 DelimiterBasedFrameDecoder服务端开发 1.1.1 EchoServer实现 import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBuf; import io.netty.b

Netty解决TCP粘包/拆包导致的半包读写问题

一.TCP粘包/拆包问题说明   TCP是个“流”协议,就是没有界限的一串数据。TCP底层并不了解上层业务数据的具体含义,它会根据TCP缓冲区的实际情况进行包拆分,所以在业务上认为,一个完整的包可能会被TCP拆分成多个包进行发送,也有可能把多个小的包封装成一个大的数据包发送,这就是所谓的TCP粘包和拆包问题。 二.利用LinedBasedFrameDecoder解决TCP粘包问题    为了