1. 程式人生 > >Netty傳送心跳 保持連線

Netty傳送心跳 保持連線

客戶端如果長期沒有傳送資料到伺服器就傳送心跳包”[LinkTest]”保持連線,如果客戶端未收到伺服器反饋資料,就傳送登入資訊”admin”, “admin”,重新登入。

在你的handler前加 socketChannel.pipeline().addLast(“ping”, new IdleStateHandler(60, 20, 60 * 10, TimeUnit.SECONDS));

Netty自己給我們提供的特別方便的操作IdleStateHandler

bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast("ping", new IdleStateHandler(60, 20, 60 * 10, TimeUnit.SECONDS)); socketChannel.pipeline().addLast(new NettyClientHandler()); } });
socketChannel.pipeline().addLast("ping", new IdleStateHandler(60, 20, 60 * 10, TimeUnit.SECONDS));
//第一個引數 60  表示讀操作空閒時間
//第二個引數 20  表示寫操作空閒時間
//第三個引數 60*10 表示讀寫操作空閒時間
//第四個引數 單位

這個就表示 如果60秒未收到伺服器資訊 就重新登入 如果20秒沒有資訊向伺服器傳送 就傳送心跳資訊

在你的handler裡面重寫userEventTriggered

   @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        // TODO Auto-generated method stub
        super.userEventTriggered
(ctx, evt); if (evt instanceof IdleStateEvent) { IdleStateEvent event = (IdleStateEvent) evt; if (event.state().equals(IdleState.READER_IDLE)) { Log.logD("------長期未收到伺服器反饋資料------"); String loginMsg = Login.login("admin", "admin"); Log.logD("------傳送登入資訊------" + loginMsg+"\r\n"); ctx.writeAndFlush(getSendByteBuf(loginMsg)); //根據具體的情況 在這裡也可以重新連線 } else if (event.state().equals(IdleState.WRITER_IDLE)) { Log.logD("------長期未向伺服器傳送資料 傳送心跳------"); Log.logD("------傳送心跳包------" + "[LinkTest]\r\n"); ctx.writeAndFlush(CodeChange.StringToBuff("[LinkTest]")); } else if (event.state().equals(IdleState.ALL_IDLE)) { } } }

主要的邏輯就是如果有資料 就向客戶端傳送資料 沒有就傳送心跳,伺服器長期沒有反饋就傳送登入資訊