netty之心跳機制

  一、心跳機制,在netty3和netty5上面都有。可是寫法有些不同。java

  二、心跳機制在服務端和客戶端的做用也是不同的。對於服務端來講:就是定時清除那些由於某種緣由在必定時間段內沒有作指定操做的客戶端鏈接。對於服務端來講:用來檢測是否斷開鏈接,而後嘗試重連等問題。遊戲上面也能夠來監控延時問題。bootstrap

  三、我這邊只寫了服務端的心跳用法,客戶端基本差很少。服務器

  1)netty3的寫法socket

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;
import org.jboss.netty.handler.timeout.IdleStateHandler;
import org.jboss.netty.util.HashedWheelTimer;

import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {

    public static void main(String[] args) {

        //聲明服務類
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //設定線程池
        ExecutorService boss = Executors.newCachedThreadPool();
        ExecutorService work = Executors.newCachedThreadPool();

        //設置工廠
        serverBootstrap.setFactory(new NioServerSocketChannelFactory(boss,work));

        //設置管道流
        serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            @Override
            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline channelPipeline = Channels.pipeline();
                //添加處理方式
                channelPipeline.addLast("idle",new IdleStateHandler(new HashedWheelTimer(),5,5,10));
                channelPipeline.addLast("decode",new StringDecoder());
                channelPipeline.addLast("encode",new StringEncoder());
                channelPipeline.addLast("server",new ServerHandler());
                return channelPipeline;
            }
        });

        //設置端口
        serverBootstrap.bind(new InetSocketAddress(9000));
    }
}

  備註:這裏和以前有變化的就是管道里面多加了一個心跳,實際的處理仍是在處理類裏面tcp

 channelPipeline.addLast("idle",new IdleStateHandler(new HashedWheelTimer(),5,5,10));
import org.jboss.netty.channel.*;
import org.jboss.netty.handler.timeout.IdleState;
import org.jboss.netty.handler.timeout.IdleStateEvent;

public class ServerHandler extends SimpleChannelHandler {

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        System.out.println("client:"+e.getMessage());
        ctx.getChannel().write(e.getMessage());
        super.messageReceived(ctx, e);
    }

    @Override
    public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
        if (e instanceof IdleStateEvent) {
            if (((IdleStateEvent)e).getState() == IdleState.ALL_IDLE) {
                ChannelFuture channelFuture = ctx.getChannel().write("Time out,You will close");
                channelFuture.addListener(channelFuture1 -> ctx.getChannel().close());
            }
        } else {
            super.handleUpstream(ctx, e);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        super.exceptionCaught(ctx, e);
    }

    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        super.channelConnected(ctx, e);
    }

    @Override
    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        super.channelDisconnected(ctx, e);
    }

    @Override
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        super.channelClosed(ctx, e);
    }
}

  說明:這裏是用SimpleChannelHandler裏面給出的事件處理來實現的。方法爲handleUpstreamide

  2)netty5的寫法和netty3差很少oop

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 serverBootstrap = new ServerBootstrap();
        //聲明兩個線程池
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup work = new NioEventLoopGroup();

        try {
            //設置線程組
            serverBootstrap.group(boss,work);
            //設置服務socket工廠
            serverBootstrap.channel(NioServerSocketChannel.class);
            //設置管道
            serverBootstrap.childHandler(new ChannelInitializer<Channel>() {
                protected void initChannel(Channel channel) throws Exception {
                    channel.pipeline().addLast(new IdleStateHandler(5,5,10));
                    channel.pipeline().addLast(new StringDecoder());
                    channel.pipeline().addLast(new StringEncoder());
                    channel.pipeline().addLast(new ServerHandler());
                }
            });
            //設置服務器鏈接數
            serverBootstrap.option(ChannelOption.SO_BACKLOG,2048);
            //設置tcp延遲狀態
            serverBootstrap.option(ChannelOption.TCP_NODELAY,true);
            //設置激活狀態,2小時清除
            serverBootstrap.option(ChannelOption.SO_KEEPALIVE,true);
            //監聽端口
            ChannelFuture channelFuture = serverBootstrap.bind(9000);
            //等待服務器關閉
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //關閉線程池
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }

    }

}
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class ServerHandler extends SimpleChannelInboundHandler<String> {

    //接收消息並處理
    protected void messageReceived(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        System.out.println(s);
        channelHandlerContext.writeAndFlush("hello client");
    }

    @Override
    public void userEventTriggered(final ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            if (((IdleStateEvent)evt).state() == IdleState.ALL_IDLE) {
                ChannelFuture channelFuture = ctx.writeAndFlush("Time out,You will close");
                channelFuture.addListener(new ChannelFutureListener() {
                    public void operationComplete(ChannelFuture channelFuture) throws Exception {
                        ctx.channel().close();
                    }
                });
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
相關文章
相關標籤/搜索