package
day4;
import
io.netty.channel.ChannelHandlerAdapter;
import
io.netty.channel.ChannelHandlerContext;
import
io.netty.util.ReferenceCountUtil;
import
java.net.InetAddress;
import
java.net.UnknownHostException;
import
java.util.concurrent.Executors;
import
java.util.concurrent.ScheduledExecutorService;
import
java.util.concurrent.ScheduledFuture;
import
java.util.concurrent.TimeUnit;
/**
* Created by zhangfengzhe on 2017/2/4.
*/
public
class
ClientHandler
extends
ChannelHandlerAdapter {
private
String ip;
private
int
port;
private
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(
1
);
private
ScheduledFuture<?> scheduledFuture;
private
static
final
String SUCCESS =
"OK"
;
public
ClientHandler(){}
public
ClientHandler(
int
port) {
this
.port = port;
try
{
this
.ip = InetAddress.getLocalHost().getHostAddress();
}
catch
(UnknownHostException e) {
e.printStackTrace();
}
}
@Override
public
void
channelActive(ChannelHandlerContext ctx)
throws
Exception {
String authInfo =
this
.ip +
":"
+
this
.port;
ctx.writeAndFlush(authInfo);
}
@Override
public
void
channelRead(ChannelHandlerContext ctx, Object msg)
throws
Exception {
if
(msg
instanceof
String){
if
(SUCCESS.equals((String)msg)){
this
.scheduledFuture = scheduledExecutorService.scheduleWithFixedDelay(
new
HeartTask(ctx,ip,port),
2
,
3
, TimeUnit.SECONDS);
}
else
{
System.out.println(
"服务器发来消息:"
+ msg);
}
}
ReferenceCountUtil.release(msg);
}
@Override
public
void
exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws
Exception {
cause.printStackTrace();
if
(
this
.scheduledFuture !=
null
){
this
.scheduledFuture.cancel(
true
);
this
.scheduledFuture =
null
;
}
}
}