客戶端如果長期沒有發送數據到服務器就發送心跳包”[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秒沒有信息向服務器發送 就發送心跳信息
在你的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)) {
}
}
}
主要的邏輯就是如果有數據 就向客戶端發送數據 沒有就發送心跳,服務器長期沒有反饋就發送登錄信息