package Demo5;
import java.net.InetSocketAddress;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
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;
/*
* 何为心跳:会话检测机制
* 服务端:定时清除闲置会话inactive(netty5) channelclose(netty3)
* 客户端:用来检测会话是否断开,是否重连! 用来检测网络延时!
* */
public class XinTiaoServer3 {
public static void main(String[] args) {
ServerBootstrap bootStrap = new ServerBootstrap();
Executor boss = Executors.newCachedThreadPool();
Executor worker = Executors.newCachedThreadPool();
bootStrap.setFactory(new NioServerSocketChannelFactory(boss, worker));
final HashedWheelTimer timer = new HashedWheelTimer();
bootStrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
//IdleStateHandler这个方法的四个param
//timer 读超时时间、写超时时间、读写超时时间
pipeline.addLast("idle", new IdleStateHandler(timer, 5, 5, 10));
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("xintiaoHandler", new XinTiaoHandler());
return pipeline;
}
});
bootStrap.bind(new InetSocketAddress(10100));
}
}
package Demo5;
import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.handler.timeout.IdleState;
import org.jboss.netty.handler.timeout.IdleStateEvent;
public class XinTiaoHandler extends SimpleChannelHandler{
/**
* 事件触发
*/
@Override
public void handleUpstream(final ChannelHandlerContext ctx, ChannelEvent evt)
throws Exception {
if(evt instanceof IdleStateEvent)
{
//No data was either received or sent for a while.
if( ((IdleStateEvent) evt).getState() == IdleState.ALL_IDLE )
{
System.out.println("提示玩家下线");
//写数据返回个客户端
ChannelFuture write = ctx.getChannel().write("time out you lost");
//给write方法添加一个侦听器
//一开始,没有进行读写操作的时候,强制关闭通道。
write.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture write) throws Exception {
// TODO Auto-generated method stub
ctx.getChannel().close();//关闭通道
}
});
}
}else{
// TODO Auto-generated method stub
super.handleUpstream(ctx, evt);
}
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
throws Exception {
// TODO Auto-generated method stub
super.messageReceived(ctx, e);
System.out.println("msg:"+(String)e.getMessage());
}
}