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() {
                @Override
                protected 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> {
    @Override
    protected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println(msg);
        ctx.writeAndFlush("回话");
    }

    @Override
    public 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() {
                    @Override
                    public 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 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.netty.channel.Channel>() {
            @Override
            protected 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> {
    @Override
    protected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println(msg);
    }
}

你可能感兴趣的